WIP cleanup/fix unit tests

This commit is contained in:
nathan 2015-07-17 02:46:00 +02:00
parent 8a26f3021e
commit a35935ff85
19 changed files with 1488 additions and 1139 deletions

View File

@ -1,15 +1,6 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
@ -21,8 +12,21 @@ import dorkbox.network.connection.EndPoint;
import dorkbox.network.util.entropy.Entropy;
import dorkbox.network.util.entropy.SimpleEntropy;
import dorkbox.network.util.exceptions.InitializationException;
import org.slf4j.LoggerFactory;
public abstract class BaseTest {
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import static org.junit.Assert.fail;
public abstract
class BaseTest {
public static final String host = "localhost";
public static final int tcpPort = 54558;
public static final int udpPort = 54779;
public static final int udtPort = 54580;
static {
// we want our entropy generation to be simple (ie, no user interaction to generate)
@ -33,20 +37,16 @@ public abstract class BaseTest {
}
}
static public String host = "localhost";
static public int tcpPort = 54558;
static public int udpPort = 54779;
static public int udtPort = 54580;
private ArrayList<EndPoint> endPoints = new ArrayList<EndPoint>();
private volatile Timer timer;
boolean fail_check;
private final ArrayList<EndPoint> endPoints = new ArrayList<EndPoint>();
private volatile Timer timer;
public BaseTest () {
public
BaseTest() {
System.out.println("---- " + getClass().getSimpleName());
// assume SLF4J is bound to logback in the current environment
Logger rootLogger = (Logger)LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
Logger rootLogger = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
LoggerContext context = rootLogger.getLoggerContext();
JoranConfigurator jc = new JoranConfigurator();
@ -90,51 +90,49 @@ public abstract class BaseTest {
rootLogger.addAppender(consoleAppender);
}
public void addEndPoint(final EndPoint endPoint) {
public
void addEndPoint(final EndPoint endPoint) {
this.endPoints.add(endPoint);
}
public void stopEndPoints() {
public
void stopEndPoints() {
stopEndPoints(0);
}
public void stopEndPoints(int stopAfterMillis) {
if (stopAfterMillis > 0) {
if (this.timer == null) {
this.timer = new Timer("UnitTest timeout timer");
}
public
void stopEndPoints(int stopAfterMillis) {
if (stopAfterMillis <= 0) {
stopAfterMillis = 1;
}
// don't automatically timeout when we are testing.
this.timer.schedule(new TimerTask() {
@Override
public void run () {
synchronized (BaseTest.this.endPoints) {
for (EndPoint endPoint : BaseTest.this.endPoints) {
endPoint.stop();
}
BaseTest.this.endPoints.clear();
if (this.timer == null) {
this.timer = new Timer("UnitTest timeout timer");
}
// We have to ALWAYS run this in a new timer, BECAUSE if stopEndPoints() is called from a client/server thread, it will DEADLOCK
this.timer.schedule(new TimerTask() {
@Override
public
void run() {
synchronized (BaseTest.this.endPoints) {
for (EndPoint endPoint : BaseTest.this.endPoints) {
endPoint.stop();
endPoint.waitForShutdown();
}
BaseTest.this.endPoints.clear();
}
if (BaseTest.this.timer != null) {
BaseTest.this.timer.cancel();
BaseTest.this.timer.purge();
BaseTest.this.timer = null;
}
}, stopAfterMillis);
} else {
synchronized (BaseTest.this.endPoints) {
for (EndPoint endPoint : BaseTest.this.endPoints) {
endPoint.stop();
}
BaseTest.this.endPoints.clear();
}
if (BaseTest.this.timer != null) {
BaseTest.this.timer.cancel();
BaseTest.this.timer.purge();
BaseTest.this.timer = null;
}
}
}, stopAfterMillis);
}
public void waitForThreads(int stopAfterSecondsOrMillis) {
public
void waitForThreads(int stopAfterSecondsOrMillis) {
if (stopAfterSecondsOrMillis < 1000) {
stopAfterSecondsOrMillis *= 1000;
}
@ -142,11 +140,13 @@ public abstract class BaseTest {
waitForThreads0(stopAfterSecondsOrMillis);
}
public void waitForThreads() {
public
void waitForThreads() {
waitForThreads0(0);
}
private void waitForThreads0(int stopAfterMillis) {
private
void waitForThreads0(int stopAfterMillis) {
this.fail_check = false;
TimerTask failTask = null;
@ -156,11 +156,12 @@ public abstract class BaseTest {
failTask = new TimerTask() {
@Override
public void run () {
public
void run() {
BaseTest.this.fail_check = true;
}
};
this.timer.schedule(failTask, stopAfterMillis+10000L);
this.timer.schedule(failTask, stopAfterMillis + 10000L);
}
while (true) {
@ -185,7 +186,7 @@ public abstract class BaseTest {
// Give sockets a chance to close before starting the next test.
try {
Thread.sleep(1000);
Thread.sleep(100);
} catch (InterruptedException ignored) {
}
}

View File

@ -2,17 +2,20 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import dorkbox.network.PingPongTest.TYPE;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.connection.idle.IdleBridge;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.fail;
public class ChunkedDataTest extends BaseTest {
private volatile boolean success = false;
@ -24,7 +27,8 @@ public class ChunkedDataTest extends BaseTest {
}
// have to test sending objects
public void ObjectSender() throws InitializationException, SecurityException {
@Test
public void ObjectSender() throws InitializationException, SecurityException, IOException {
final Data mainData = new Data();
populateData(mainData);
@ -33,6 +37,9 @@ public class ChunkedDataTest extends BaseTest {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -41,7 +48,10 @@ public class ChunkedDataTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
sendObject(mainData, connectionOptions, ConnectionType.TCP);
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.UDP);
System.err.println("-- UDT");
@ -49,15 +59,19 @@ public class ChunkedDataTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
sendObject(mainData, connectionOptions, ConnectionType.TCP);
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.UDT);
}
private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException {
private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.setIdleTimeout(100);
server.bind(false);
@ -82,7 +96,6 @@ public class ChunkedDataTest extends BaseTest {
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<Data>() {
@Override
@ -133,7 +146,7 @@ public class ChunkedDataTest extends BaseTest {
data.Booleans = new Boolean[] {true, false};
}
private void register (SerializationManager kryoMT) {
private void register (ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class);
kryoMT.register(short[].class);
kryoMT.register(float[].class);

View File

@ -1,58 +1,66 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ClientSendTest extends BaseTest {
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.junit.Assert.fail;
public
class ClientSendTest extends BaseTest {
private AtomicBoolean checkPassed = new AtomicBoolean(false);
@Test
public void sendDataFromClientClass () throws InitializationException, SecurityException {
public
void sendDataFromClientClass() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
register(server.getSerialization());
server.listeners().add(new Listener<AMessage>() {
@Override
public void received (Connection connection, AMessage object) {
System.err.println("Server received message from client. Bouncing back.");
connection.send().TCP(object);
}
});
server.listeners()
.add(new Listener<AMessage>() {
@Override
public
void received(Connection connection, AMessage object) {
System.err.println("Server received message from client. Bouncing back.");
connection.send()
.TCP(object);
}
});
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
register(client.getSerialization());
client.connect(5000);
client.listeners().add(new Listener<AMessage>() {
@Override
public void received (Connection connection, AMessage object) {
ClientSendTest.this.checkPassed.set(true);
stopEndPoints();
}
});
client.listeners()
.add(new Listener<AMessage>() {
@Override
public
void received(Connection connection, AMessage object) {
ClientSendTest.this.checkPassed.set(true);
stopEndPoints();
}
});
client.send().TCP(new AMessage());
client.send()
.TCP(new AMessage());
waitForThreads();
@ -61,12 +69,15 @@ public class ClientSendTest extends BaseTest {
}
}
private void register (SerializationManager kryoMT) {
private static
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(AMessage.class);
}
public static class AMessage {
public AMessage () {
public static
class AMessage {
public
AMessage() {
}
}
}

View File

@ -1,161 +1,187 @@
package dorkbox.network;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class ConnectionTest extends BaseTest {
public
class ConnectionTest extends BaseTest {
@Test
public void connectLocal() throws InitializationException, SecurityException {
public
void connectLocal() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "Local");
startServer(null);
startClient(null);
ConnectionOptions connectionOptions = new ConnectionOptions(EndPoint.LOCAL_CHANNEL);
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
startServer(connectionOptions);
startClient(connectionOptions);
waitForThreads(10);
}
@Test
public void connectTcp() throws InitializationException, SecurityException {
public
void connectTcp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP");
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions);
startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10);
}
@Test
public void connectTcpUdp() throws InitializationException, SecurityException {
public
void connectTcpUdp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP");
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions);
startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10);
}
@Test
public void connectTcpUdt() throws InitializationException, SecurityException {
public
void connectTcpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions);
startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10);
}
@Test
public void connectTcpUdpUdt() throws InitializationException, SecurityException {
public
void connectTcpUdpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = startServer(connectionOptions);
startServer(connectionOptions);
connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10);
}
private Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException {
Server server;
if (connectionOptions != null) {
server = new Server(connectionOptions);
} else {
server = new Server();
}
private
Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
server.listeners().add(new Listener<Object>() {
Timer timer = new Timer();
@Override
public void connected (final Connection connection) {
this.timer.schedule(new TimerTask() {
@Override
public void run () {
System.out.println("Disconnecting after 1 second.");
connection.close();
}
}, 1000);
}
});
server.bind(false);
server.listeners()
.add(new Listener<Object>() {
Timer timer = new Timer();
@Override
public
void connected(final Connection connection) {
this.timer.schedule(new TimerTask() {
@Override
public
void run() {
System.out.println("Disconnecting after 1 second.");
connection.close();
}
}, 1000);
}
@Override
public void received(Connection connection, Object message) {
System.err.println("Received message from client: " + message.getClass().getSimpleName());
}
});
return server;
}
private Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException {
private
Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
Client client;
if (connectionOptions != null) {
client = new Client(connectionOptions);
} else {
}
else {
client = new Client();
}
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<Object>() {
@Override
public void disconnected(Connection connection) {
stopEndPoints();
}
});
client.listeners()
.add(new Listener<Object>() {
@Override
public
void disconnected(Connection connection) {
stopEndPoints();
}
});
client.connect(5000);
client.send()
.TCP(new BMessage())
.flush();
return client;
}
private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(BMessage.class);
}
public static
class BMessage {
public
BMessage() {
}
}
}

View File

@ -1,21 +1,23 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class DiscoverHostTest extends BaseTest {
import java.io.IOException;
import static org.junit.Assert.fail;
public
class DiscoverHostTest extends BaseTest {
volatile boolean connected = false;
@Test
public void broadcast () throws InitializationException, SecurityException {
public
void broadcast() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
@ -39,13 +41,15 @@ public class DiscoverHostTest extends BaseTest {
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<Object>() {
@Override
public void connected(Connection connection) {
DiscoverHostTest.this.connected = true;
stopEndPoints();
}
});
client.listeners()
.add(new Listener<Object>() {
@Override
public
void connected(Connection connection) {
DiscoverHostTest.this.connected = true;
stopEndPoints();
}
});
client.connect(2000);
waitForThreads(2);

View File

@ -1,28 +1,30 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.junit.Test;
import dorkbox.network.PingPongTest.TYPE;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.connection.idle.IdleBridge;
import dorkbox.network.connection.idle.InputStreamSender;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.fail;
@SuppressWarnings({"rawtypes"})
public class IdleTest extends BaseTest {
public
class IdleTest extends BaseTest {
private volatile boolean success = false;
enum ConnectionType {
TCP,
UDP,
@ -30,13 +32,15 @@ public class IdleTest extends BaseTest {
}
@Test
public void InputStreamSender() throws InitializationException, SecurityException {
public
void InputStreamSender() throws InitializationException, SecurityException, IOException {
final int largeDataSize = 12345;
System.err.println("-- TCP");
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.TCP);
@ -45,6 +49,7 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDP);
@ -53,6 +58,7 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
streamSpecificType(largeDataSize, connectionOptions, ConnectionType.UDT);
}
@ -60,7 +66,8 @@ public class IdleTest extends BaseTest {
// have to test sending objects
@Test
public void ObjectSender() throws InitializationException, SecurityException {
public
void ObjectSender() throws InitializationException, SecurityException, IOException {
final Data mainData = new Data();
populateData(mainData);
@ -69,6 +76,8 @@ public class IdleTest extends BaseTest {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -77,6 +86,8 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP);
@ -85,49 +96,61 @@ public class IdleTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
sendObject(mainData, connectionOptions, ConnectionType.TCP);
}
private void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException {
private
void sendObject(final Data mainData, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.setIdleTimeout(100);
server.bind(false);
server.listeners().add(new Listener<Data>() {
server.listeners()
.add(new Listener<Data>() {
@Override
public void connected (Connection connection) {
IdleBridge sendOnIdle = connection.sendOnIdle(mainData);
@Override
public
void connected(Connection connection) {
IdleBridge sendOnIdle = connection.sendOnIdle(mainData);
switch (type) {
case TCP: sendOnIdle.TCP(); break;
case UDP: sendOnIdle.UDP(); break;
case UDT: sendOnIdle.UDT(); break;
}
}
});
switch (type) {
case TCP:
sendOnIdle.TCP();
break;
case UDP:
sendOnIdle.UDP();
break;
case UDT:
sendOnIdle.UDT();
break;
}
}
});
// ----
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<Data>() {
@Override
public void received(Connection connection, Data object) {
if (mainData.equals(object)) {
IdleTest.this.success = true;
}
client.listeners()
.add(new Listener<Data>() {
@Override
public
void received(Connection connection, Data object) {
if (mainData.equals(object)) {
IdleTest.this.success = true;
}
System.err.println("finished!");
stopEndPoints();
}
});
System.err.println("finished!");
stopEndPoints();
}
});
client.connect(5000);
@ -139,67 +162,79 @@ public class IdleTest extends BaseTest {
private void streamSpecificType(final int largeDataSize, ConnectionOptions connectionOptions, final ConnectionType type) throws InitializationException, SecurityException {
private
void streamSpecificType(final int largeDataSize, ConnectionOptions connectionOptions, final ConnectionType type)
throws InitializationException, SecurityException, IOException {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
server.getSerialization().setRegistrationRequired(false);
addEndPoint(server);
server.setIdleTimeout(100);
server.bind(false);
server.listeners().add(new Listener<byte[]>() {
@Override
public void connected (Connection connection) {
ByteArrayOutputStream output = new ByteArrayOutputStream(largeDataSize);
for (int i = 0; i < largeDataSize; i++) {
output.write(i);
}
server.listeners()
.add(new Listener<byte[]>() {
@Override
public
void connected(Connection connection) {
ByteArrayOutputStream output = new ByteArrayOutputStream(largeDataSize);
for (int i = 0; i < largeDataSize; i++) {
output.write(i);
}
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
// Send data in 512 byte chunks.
IdleBridge sendOnIdle = connection.sendOnIdle(new InputStreamSender(input, 512) {
@Override
protected void start () {
// Normally would send an object so the receiving side knows how to handle the chunks we are about to send.
System.err.println("starting");
}
// Send data in 512 byte chunks.
IdleBridge sendOnIdle = connection.sendOnIdle(new InputStreamSender(input, 512) {
@Override
protected
void start() {
// Normally would send an object so the receiving side knows how to handle the chunks we are about to send.
System.err.println("starting");
}
@Override
protected byte[] onNext (byte[] bytes) {
//System.out.println("sending " + bytes.length);
return bytes; // Normally would wrap the byte[] with an object so the receiving side knows how to handle it.
}
});
@Override
protected
byte[] onNext(byte[] bytes) {
//System.out.println("sending " + bytes.length);
return bytes; // Normally would wrap the byte[] with an object so the receiving side knows how to handle it.
}
});
switch (type) {
case TCP: sendOnIdle.TCP(); break;
case UDP: sendOnIdle.UDP(); break;
case UDT: sendOnIdle.UDT(); break;
}
}
});
switch (type) {
case TCP:
sendOnIdle.TCP();
break;
case UDP:
sendOnIdle.UDP();
break;
case UDT:
sendOnIdle.UDT();
break;
}
}
});
// ----
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
client.getSerialization().setRegistrationRequired(false);
addEndPoint(client);
client.listeners().add(new Listener<byte[]>() {
int total;
client.listeners()
.add(new Listener<byte[]>() {
int total;
@Override
public void received (Connection connection, byte[] object) {
int length = object.length;
//System.err.println("received " + length);
this.total += length;
if (this.total == largeDataSize) {
IdleTest.this.success = true;
System.err.println("finished!");
stopEndPoints();
}
}
});
@Override
public
void received(Connection connection, byte[] object) {
int length = object.length;
//System.err.println("received " + length);
this.total += length;
if (this.total == largeDataSize) {
IdleTest.this.success = true;
System.err.println("finished!");
stopEndPoints();
}
}
});
client.connect(5000);
@ -210,7 +245,8 @@ public class IdleTest extends BaseTest {
}
private void populateData(Data data) {
private
void populateData(Data data) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 3000; i++) {
buffer.append('a');
@ -220,7 +256,7 @@ public class IdleTest extends BaseTest {
data.strings = new String[] {"abcdefghijklmnopqrstuvwxyz0123456789", "", null, "!@#$", "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"};
data.ints = new int[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.shorts = new short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.doubles = new double[] {0, -0, 1, -1, 123456, -123456, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.longs = new long[] {0, -0, 1, -1, 123456, -123456, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
@ -230,7 +266,8 @@ public class IdleTest extends BaseTest {
data.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -238,7 +275,8 @@ public class IdleTest extends BaseTest {
data.Booleans = new Boolean[] {true, false};
}
private void register (SerializationManager kryoMT) {
private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class);
kryoMT.register(short[].class);
kryoMT.register(float[].class);
@ -260,7 +298,8 @@ public class IdleTest extends BaseTest {
kryoMT.register(TYPE.class);
}
static public class Data {
static public
class Data {
public String string;
public String[] strings;
public int[] ints;
@ -282,7 +321,8 @@ public class IdleTest extends BaseTest {
@Override
public int hashCode() {
public
int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans);
@ -307,7 +347,8 @@ public class IdleTest extends BaseTest {
}
@Override
public boolean equals(Object obj) {
public
boolean equals(Object obj) {
if (this == obj) {
return true;
}
@ -370,7 +411,8 @@ public class IdleTest extends BaseTest {
if (other.string != null) {
return false;
}
} else if (!this.string.equals(other.string)) {
}
else if (!this.string.equals(other.string)) {
return false;
}
if (!Arrays.equals(this.strings, other.strings)) {
@ -380,7 +422,8 @@ public class IdleTest extends BaseTest {
}
@Override
public String toString () {
public
String toString() {
return "Data";
}
}

View File

@ -2,18 +2,19 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import static org.junit.Assert.fail;
public class LargeBufferTest extends BaseTest {
private static final int OBJ_SIZE = 1024 * 10;
@ -23,19 +24,20 @@ public class LargeBufferTest extends BaseTest {
private volatile int clientCheck = -1;
@Test
public void manyLargeMessages () throws InitializationException, SecurityException {
public void manyLargeMessages () throws InitializationException, SecurityException, IOException {
final int messageCount = 1024;
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
register(server.getSerialization());
server.listeners().add(new Listener<LargeMessage>() {
AtomicInteger received = new AtomicInteger();
@ -60,7 +62,6 @@ public class LargeBufferTest extends BaseTest {
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
register(client.getSerialization());
client.connect(5000);
client.listeners().add(new Listener<LargeMessage>() {
@ -105,7 +106,7 @@ public class LargeBufferTest extends BaseTest {
}
}
private void register (SerializationManager kryoMT) {
private void register (ConnectionSerializationManager kryoMT) {
kryoMT.register(byte[].class);
kryoMT.register(LargeMessage.class);
}

View File

@ -1,24 +1,19 @@
package dorkbox.network;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import dorkbox.network.connection.*;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import static org.junit.Assert.*;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.ConnectionImpl;
import dorkbox.network.connection.Listener;
import dorkbox.network.connection.ListenerRaw;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class ListenerTest extends BaseTest {
public
class ListenerTest extends BaseTest {
private final String origString = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; // lots of a's to encourage compression
private final int limit = 20;
@ -31,24 +26,30 @@ public class ListenerTest extends BaseTest {
AtomicBoolean superClass2WorkedOK = new AtomicBoolean(false);
AtomicBoolean disconnectWorkedOK = new AtomicBoolean(false);
// quick and dirty test to also test connection sub-classing
class TestConnectionA extends ConnectionImpl {
public TestConnectionA(String name) {
super(name);
public
TestConnectionA(Class<? extends EndPoint> type) {
super(type);
}
public void check() {
public
void check() {
ListenerTest.this.subClassWorkedOK.set(true);
}
}
class TestConnectionB extends TestConnectionA {
public TestConnectionB(String name) {
super(name);
public
TestConnectionB(Class<? extends EndPoint> type) {
super(type);
}
@Override
public void check() {
public
void check() {
ListenerTest.this.subClassWorkedOK.set(true);
}
}
@ -57,15 +58,17 @@ public class ListenerTest extends BaseTest {
@SuppressWarnings("rawtypes")
@Test
public void listener() throws SecurityException, InitializationException {
public
void listener() throws SecurityException, InitializationException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
Server server = new Server(connectionOptions) {
@Override
public TestConnectionA newConnection(String name) {
return new TestConnectionA(name);
public
TestConnectionA newConnection(Class<? extends EndPoint> type) {
return new TestConnectionA(type);
}
};
@ -73,60 +76,74 @@ public class ListenerTest extends BaseTest {
addEndPoint(server);
server.bind(false);
server.listeners().add(new ListenerRaw<TestConnectionA, String>() {
@Override
public void received (TestConnectionA connection, String string) {
connection.check();
server.listeners()
.add(new ListenerRaw<TestConnectionA, String>() {
@Override
public
void received(TestConnectionA connection, String string) {
connection.check();
// System.err.println("default check");
connection.send().TCP(string);
}
});
connection.send()
.TCP(string);
}
});
server.listeners().add(new Listener<String>() {
@Override
public void received (Connection connection, String string) {
server.listeners()
.add(new Listener<String>() {
@Override
public
void received(Connection connection, String string) {
// System.err.println("subclass check");
ListenerTest.this.subClassWorkedOK2.set(true);
}
});
ListenerTest.this.subClassWorkedOK2.set(true);
}
});
// should be able to happen!
server.listeners().add(new Listener() {
@Override
public void received(Connection connection, Object string) {
server.listeners()
.add(new Listener() {
@Override
public
void received(Connection connection, Object string) {
// System.err.println("generic class check");
ListenerTest.this.superClassWorkedOK.set(true);
}
});
ListenerTest.this.superClassWorkedOK.set(true);
}
});
// should be able to happen!
server.listeners().add(new ListenerRaw() {
@Override
public void received(Connection connection, Object string) {
server.listeners()
.add(new ListenerRaw() {
@Override
public
void received(Connection connection, Object string) {
// System.err.println("generic class check");
ListenerTest.this.superClass2WorkedOK.set(true);
}
});
ListenerTest.this.superClass2WorkedOK.set(true);
}
});
server.listeners().add(new Listener() {
@Override
public void disconnected(Connection connection) {
server.listeners()
.add(new Listener() {
@Override
public
void disconnected(Connection connection) {
// System.err.println("disconnect check");
ListenerTest.this.disconnectWorkedOK.set(true);
}
});
ListenerTest.this.disconnectWorkedOK.set(true);
}
});
// should not let this happen!
try {
server.listeners().add(new ListenerRaw<TestConnectionB, String>() {
@Override
public void received (TestConnectionB connection, String string) {
connection.check();
System.err.println(string);
connection.send().TCP(string);
}
});
server.listeners()
.add(new ListenerRaw<TestConnectionB, String>() {
@Override
public
void received(TestConnectionB connection, String string) {
connection.check();
System.err.println(string);
connection.send()
.TCP(string);
}
});
this.fail = "Should not be able to ADD listeners that are NOT the basetype or the interface";
} catch (Exception e) {
System.err.println("Successfully did NOT add listener that was not the base class");
@ -139,25 +156,31 @@ public class ListenerTest extends BaseTest {
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP(ListenerTest.this.origString); // 20 a's
}
client.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP(ListenerTest.this.origString); // 20 a's
}
@Override
public void received (Connection connection, String string) {
if (ListenerTest.this.count.get() < ListenerTest.this.limit) {
ListenerTest.this.count.getAndIncrement();
connection.send().TCP(string);
} else {
if (!ListenerTest.this.origString.equals(string)) {
ListenerTest.this.fail = "original string not equal to the string received";
}
stopEndPoints();
}
}
});
@Override
public
void received(Connection connection, String string) {
if (ListenerTest.this.count.get() < ListenerTest.this.limit) {
ListenerTest.this.count.getAndIncrement();
connection.send()
.TCP(string);
}
else {
if (!ListenerTest.this.origString.equals(string)) {
ListenerTest.this.fail = "original string not equal to the string received";
}
stopEndPoints();
}
}
});
client.connect(5000);

View File

@ -1,69 +1,76 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class MultipleServerTest extends BaseTest {
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class MultipleServerTest extends BaseTest {
AtomicInteger received = new AtomicInteger();
@Test
public void multipleServers() throws InitializationException, SecurityException {
public
void multipleServers() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions1 = new ConnectionOptions();
connectionOptions1.tcpPort = tcpPort;
connectionOptions1.udpPort = udpPort;
connectionOptions1.localChannelName = "chan1";
connectionOptions1.serializationManager = KryoConnectionSerializationManager.DEFAULT();
connectionOptions1.serializationManager.register(String[].class);
Server server1 = new Server(connectionOptions1);
server1.disableRemoteKeyValidation();
server1.getSerialization().register(String[].class);
addEndPoint(server1);
server1.bind(false);
server1.listeners().add(new Listener<String>() {
@Override
public void received (Connection connection, String object) {
if (!object.equals("client1")) {
fail();
}
if (MultipleServerTest.this.received.incrementAndGet() == 2) {
stopEndPoints();
}
}
});
server1.listeners()
.add(new Listener<String>() {
@Override
public
void received(Connection connection, String object) {
if (!object.equals("client1")) {
fail();
}
if (MultipleServerTest.this.received.incrementAndGet() == 2) {
stopEndPoints();
}
}
});
ConnectionOptions connectionOptions2 = new ConnectionOptions();
connectionOptions2.tcpPort = tcpPort+1;
connectionOptions2.udpPort = udpPort+1;
connectionOptions2.tcpPort = tcpPort + 1;
connectionOptions2.udpPort = udpPort + 1;
connectionOptions2.localChannelName = "chan2";
connectionOptions2.serializationManager = KryoConnectionSerializationManager.DEFAULT();
connectionOptions2.serializationManager.register(String[].class);
Server server2 = new Server(connectionOptions2);
server2.disableRemoteKeyValidation();
server2.getSerialization().register(String[].class);
addEndPoint(server2);
server2.bind(false);
server2.listeners().add(new Listener<String>() {
@Override
public void received (Connection connection, String object) {
if (!object.equals("client2")) {
fail();
}
if (MultipleServerTest.this.received.incrementAndGet() == 2) {
stopEndPoints();
}
}
});
server2.listeners()
.add(new Listener<String>() {
@Override
public
void received(Connection connection, String object) {
if (!object.equals("client2")) {
fail();
}
if (MultipleServerTest.this.received.incrementAndGet() == 2) {
stopEndPoints();
}
}
});
// ----
@ -72,14 +79,16 @@ public class MultipleServerTest extends BaseTest {
Client client1 = new Client(connectionOptions1);
client1.disableRemoteKeyValidation();
client1.getSerialization().register(String[].class);
addEndPoint(client1);
client1.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("client1");
}
});
client1.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("client1");
}
});
client1.connect(5000);
@ -88,14 +97,16 @@ public class MultipleServerTest extends BaseTest {
Client client2 = new Client(connectionOptions2);
client2.disableRemoteKeyValidation();
client2.getSerialization().register(String[].class);
addEndPoint(client2);
client2.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("client2");
}
});
client2.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("client2");
}
});
client2.connect(5000);
waitForThreads(30);

View File

@ -1,23 +1,24 @@
package dorkbox.network;
import static org.junit.Assert.assertEquals;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class MultipleThreadTest extends BaseTest {
public
class MultipleThreadTest extends BaseTest {
AtomicInteger sent = new AtomicInteger(0);
AtomicInteger totalClientCounter = new AtomicInteger(1);
AtomicInteger receivedServer = new AtomicInteger(1);
@ -29,61 +30,73 @@ public class MultipleThreadTest extends BaseTest {
private final int threadCount = 15;
private final int clientCount = 13;
private List<Client> clients = new ArrayList<Client>(this.clientCount);
private final List<Client> clients = new ArrayList<Client>(this.clientCount);
@Test
public void multipleThreads () throws InitializationException, SecurityException {
public
void multipleThreads() throws InitializationException, SecurityException, IOException {
final KryoConnectionSerializationManager serializationManager = KryoConnectionSerializationManager.DEFAULT(false, true);
serializationManager.register(String[].class);
serializationManager.register(DataClass.class);
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = serializationManager;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
server.getSerialization().register(String[].class);
server.getSerialization().register(DataClass.class);
addEndPoint(server);
server.bind(false);
server.listeners().add(new Listener<DataClass>() {
@Override
public void connected(final Connection connection) {
System.err.println("Client connected to server.");
server.listeners()
.add(new Listener<DataClass>() {
@Override
public
void connected(final Connection connection) {
System.err.println("Client connected to server.");
// kickoff however many threads we need, and send data to the client.
for (int i = 1; i <= MultipleThreadTest.this.threadCount; i++) {
final int index = i;
new Thread() {
@Override
public void run () {
for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) {
int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement();
DataClass dataClass = new DataClass("Server -> client. Thread #" + index + " message# " + incrementAndGet, incrementAndGet);
MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass);
connection.send().TCP(dataClass).flush();
}
}
}.start();
}
}
// kickoff however many threads we need, and send data to the client.
for (int i = 1; i <= MultipleThreadTest.this.threadCount; i++) {
final int index = i;
new Thread() {
@Override
public
void run() {
for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) {
int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement();
DataClass dataClass = new DataClass(
"Server -> client. Thread #" + index + " message# " + incrementAndGet,
incrementAndGet);
MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass);
connection.send()
.TCP(dataClass)
.flush();
}
}
}.start();
}
}
@Override
public void received (Connection connection, DataClass object) {
int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement();
@Override
public
void received(Connection connection, DataClass object) {
int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement();
if (incrementAndGet == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.clientCount) {
System.err.println("Server DONE " + incrementAndGet);
// note. this is getting called BEFORE it's ready?
stopEndPoints();
synchronized (MultipleThreadTest.this.lock) {
MultipleThreadTest.this.lock.notifyAll();
}
}
}
});
if (incrementAndGet == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.clientCount) {
System.err.println("Server DONE " + incrementAndGet);
// note. this is getting called BEFORE it's ready?
stopEndPoints();
synchronized (MultipleThreadTest.this.lock) {
MultipleThreadTest.this.lock.notifyAll();
}
}
}
});
// ----
@ -94,32 +107,37 @@ public class MultipleThreadTest extends BaseTest {
client.disableRemoteKeyValidation();
this.clients.add(client);
client.getSerialization().register(String[].class);
client.getSerialization().register(DataClass.class);
addEndPoint(client);
client.listeners().add(new Listener<DataClass>() {
AtomicInteger received = new AtomicInteger(1);
client.listeners()
.add(new Listener<DataClass>() {
AtomicInteger received = new AtomicInteger(1);
@Override
public void connected(Connection connection) {
System.err.println("Client #" + index + " connected.");
}
@Override
public
void connected(Connection connection) {
System.err.println("Client #" + index + " connected.");
}
@Override
public void received (Connection connection, DataClass object) {
int clientLocalCounter = this.received.getAndIncrement();
MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index);
@Override
public
void received(Connection connection, DataClass object) {
int clientLocalCounter = this.received.getAndIncrement();
MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index);
// we finished!!
if (clientLocalCounter == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.threadCount) {
System.err.println("Client #" + index + " received " + clientLocalCounter + " (" + MultipleThreadTest.this.totalClientCounter.getAndIncrement() + ") Sending back " + MultipleThreadTest.this.messageCount + " messages.");
// now spam back messages!
for (int i = 0; i < MultipleThreadTest.this.messageCount; i++) {
connection.send().TCP(new DataClass("Client #" + index + " -> Server message " + i, index));
}
}
}
});
// we finished!!
if (clientLocalCounter == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.threadCount) {
System.err.println("Client #" + index + " received " + clientLocalCounter + " (" +
MultipleThreadTest.this.totalClientCounter.getAndIncrement() + ") Sending back " +
MultipleThreadTest.this.messageCount + " messages.");
// now spam back messages!
for (int i = 0; i < MultipleThreadTest.this.messageCount; i++) {
connection.send()
.TCP(new DataClass("Client #" + index + " -> Server message " + i, index));
}
}
}
});
client.connect(5000);
}
@ -127,7 +145,8 @@ public class MultipleThreadTest extends BaseTest {
// the ONLY way to safely work in the server is with LISTENERS. Everything else can FAIL, because of it's async. nature.
// our clients should receive messageCount * threadCount * clientCount TOTAL messages
System.err.println("SEND COUNTS: " + this.threadCount * this.clientCount * this.messageCount + " and then " + this.messageCount * this.clientCount + " total messages");
System.err.println("SEND COUNTS: " + this.threadCount * this.clientCount * this.messageCount + " and then " +
this.messageCount * this.clientCount + " total messages");
synchronized (this.lock) {
try {
@ -145,17 +164,20 @@ public class MultipleThreadTest extends BaseTest {
}
stopEndPoints();
assertEquals(this.messageCount * this.clientCount, this.receivedServer.get()-1); // offset by 1 since we start at 1.
assertEquals(this.messageCount * this.clientCount, this.receivedServer.get() - 1); // offset by 1 since we start at 1.
}
public static class DataClass {
public static
class DataClass {
public String data;
public Integer index;
public DataClass() {
public
DataClass() {
}
public DataClass(String data, Integer index) {
public
DataClass(String data, Integer index) {
this.data = data;
this.index = index;
}

View File

@ -1,25 +1,25 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import static org.junit.Assert.fail;
public class PingPongLocalTest extends BaseTest {
private volatile String fail;
int tries = 10000;
@Test
public void pingPongLocal() throws InitializationException, SecurityException {
public void pingPongLocal() throws InitializationException, SecurityException, IOException {
this.fail = "Data not received.";
final Data dataLOCAL = new Data();
@ -126,7 +126,7 @@ public class PingPongLocalTest extends BaseTest {
data.Booleans = new Boolean[] {true,false};
}
private void register(SerializationManager kryoMT) {
private void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class);
kryoMT.register(short[].class);
kryoMT.register(float[].class);

View File

@ -1,33 +1,36 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class PingPongTest extends BaseTest {
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class PingPongTest extends BaseTest {
private volatile String fail;
int tries = 1000;
enum TYPE {
TCP, UDP, UDT
}
@Test
public void pingPong () throws InitializationException, SecurityException {
public
void pingPong() throws InitializationException, SecurityException, IOException {
// UDP data is kinda big. Make sure it fits into one packet.
int origSize = EndPoint.udpMaxSize;
EndPoint.udpMaxSize = 2048;
@ -39,6 +42,8 @@ public class PingPongTest extends BaseTest {
connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
final Data dataTCP = new Data();
populateData(dataTCP, TYPE.TCP);
@ -50,118 +55,138 @@ public class PingPongTest extends BaseTest {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
register(server.getSerialization());
server.bind(false);
server.listeners().add(new Listener<Data>() {
@Override
public void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable;
}
server.listeners()
.add(new Listener<Data>() {
@Override
public
void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable;
}
@Override
public void received (Connection connection, Data data) {
if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send().TCP(data);
}
else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send().UDP(data);
}
else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send().UDT(data);
}
else {
PingPongTest.this.fail = "Unknown data type on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
}
});
@Override
public
void received(Connection connection, Data data) {
if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send()
.TCP(data);
}
else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send()
.UDP(data);
}
else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
connection.send()
.UDT(data);
}
else {
PingPongTest.this.fail = "Unknown data type on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
}
});
// ----
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
register(client.getSerialization());
client.listeners().add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0);
AtomicInteger checkUDT = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false);
AtomicBoolean doneUDT = new AtomicBoolean(false);
client.listeners()
.add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0);
AtomicInteger checkUDT = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false);
AtomicBoolean doneUDT = new AtomicBoolean(false);
@Override
public void connected (Connection connection) {
PingPongTest.this.fail = null;
connection.send().TCP(dataTCP);
connection.send().UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
connection.send().UDT(dataUDT);
}
@Override
public
void connected(Connection connection) {
PingPongTest.this.fail = null;
connection.send()
.TCP(dataTCP);
connection.send()
.UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
connection.send()
.UDT(dataUDT);
}
@Override
public void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable;
throwable.printStackTrace();
}
@Override
public
void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable;
throwable.printStackTrace();
}
@Override
public void received (Connection connection, Data data) {
if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkTCP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().TCP(data);
} else {
System.err.println("TCP done.");
this.doneTCP.set(true);
}
} else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().UDP(data);
} else {
System.err.println("UDP done.");
this.doneUDP.set(true);
}
} else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) {
connection.send().UDT(data);
} else {
System.err.println("UDT done.");
this.doneUDT.set(true);
}
} else {
PingPongTest.this.fail = "Unknown data type on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
@Override
public
void received(Connection connection, Data data) {
if (data.type == TYPE.TCP) {
if (!data.equals(dataTCP)) {
PingPongTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkTCP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send()
.TCP(data);
}
else {
System.err.println("TCP done.");
this.doneTCP.set(true);
}
}
else if (data.type == TYPE.UDP) {
if (!data.equals(dataUDP)) {
PingPongTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) {
connection.send()
.UDP(data);
}
else {
System.err.println("UDP done.");
this.doneUDP.set(true);
}
}
else if (data.type == TYPE.UDT) {
if (!data.equals(dataUDT)) {
PingPongTest.this.fail = "UDT data is not equal on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) {
connection.send()
.UDT(data);
}
else {
System.err.println("UDT done.");
this.doneUDT.set(true);
}
}
else {
PingPongTest.this.fail = "Unknown data type on client.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
if (this.doneTCP.get() && this.doneUDP.get() && this.doneUDT.get()) {
System.err.println("Ran TCP, UDP, UDT " + PingPongTest.this.tries + " times each");
stopEndPoints();
}
}
});
if (this.doneTCP.get() && this.doneUDP.get() && this.doneUDT.get()) {
System.err.println("Ran TCP, UDP, UDT " + PingPongTest.this.tries + " times each");
stopEndPoints();
}
}
});
client.connect(5000);
@ -174,7 +199,8 @@ public class PingPongTest extends BaseTest {
EndPoint.udpMaxSize = origSize;
}
private void populateData (Data data, TYPE type) {
private
void populateData(Data data, TYPE type) {
data.type = type;
StringBuilder buffer = new StringBuilder();
@ -186,7 +212,7 @@ public class PingPongTest extends BaseTest {
data.strings = new String[] {"abcdefghijklmnopqrstuvwxyz0123456789", "", null, "!@#$", "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"};
data.ints = new int[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.shorts = new short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.doubles = new double[] {0, -0, 1, -1, 123456, -123456, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.longs = new long[] {0, -0, 1, -1, 123456, -123456, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
@ -196,7 +222,8 @@ public class PingPongTest extends BaseTest {
data.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -204,7 +231,8 @@ public class PingPongTest extends BaseTest {
data.Booleans = new Boolean[] {true, false};
}
private void register (SerializationManager kryoMT) {
private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class);
kryoMT.register(short[].class);
kryoMT.register(float[].class);
@ -226,7 +254,8 @@ public class PingPongTest extends BaseTest {
kryoMT.register(TYPE.class);
}
static public class Data {
static public
class Data {
public TYPE type;
public String string;
public String[] strings;
@ -249,7 +278,8 @@ public class PingPongTest extends BaseTest {
@Override
public int hashCode() {
public
int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans);
@ -275,7 +305,8 @@ public class PingPongTest extends BaseTest {
}
@Override
public boolean equals(Object obj) {
public
boolean equals(Object obj) {
if (this == obj) {
return true;
}
@ -338,7 +369,8 @@ public class PingPongTest extends BaseTest {
if (other.string != null) {
return false;
}
} else if (!this.string.equals(other.string)) {
}
else if (!this.string.equals(other.string)) {
return false;
}
if (!Arrays.equals(this.strings, other.strings)) {
@ -351,7 +383,8 @@ public class PingPongTest extends BaseTest {
}
@Override
public String toString () {
public
String toString() {
return "Data";
}
}

View File

@ -1,25 +1,27 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Ping;
import dorkbox.network.connection.PingListener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.fail;
public class PingTest extends BaseTest {
public
class PingTest extends BaseTest {
private volatile int response = -1;
// ping prefers the following order: UDP, UDT, TCP
@Test
public void pingTCP() throws InitializationException, SecurityException {
public
void pingTCP() throws InitializationException, SecurityException, IOException {
this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -40,8 +42,10 @@ public class PingTest extends BaseTest {
client.connect(5000);
System.err.println("Testing TCP ping");
for (int i=0;i<10;i++) {
this.response = client.send().ping().getResponse();
for (int i = 0; i < 10; i++) {
this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response);
}
@ -52,7 +56,8 @@ public class PingTest extends BaseTest {
}
@Test
public void pingTCP_testListeners1() throws InitializationException, SecurityException {
public
void pingTCP_testListeners1() throws InitializationException, SecurityException, IOException {
this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -78,12 +83,16 @@ public class PingTest extends BaseTest {
volatile int count = 0;
@Override
public void response(Connection connection, int pingResponseTime) {
public
void response(Connection connection, int pingResponseTime) {
System.err.println("Ping: " + pingResponseTime);
if (this.count++ < 10) {
connection.send().ping().addListener(this);
} else {
connection.send()
.ping()
.addListener(this);
}
else {
PingTest.this.response = pingResponseTime;
stopEndPoints();
}
@ -92,7 +101,8 @@ public class PingTest extends BaseTest {
// alternate way to register for the receipt of a one-off ping response
// doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten
Ping ping = client.send().ping();
Ping ping = client.send()
.ping();
ping.addListener(pingListener);
waitForThreads();
@ -103,7 +113,8 @@ public class PingTest extends BaseTest {
}
@Test
public void pingTCP_testListeners2() throws InitializationException, SecurityException {
public
void pingTCP_testListeners2() throws InitializationException, SecurityException, IOException {
this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -127,7 +138,8 @@ public class PingTest extends BaseTest {
final PingListener<Connection> pingListener = new PingListener<Connection>() {
@Override
public void response(Connection connection, int pingResponseTime) {
public
void response(Connection connection, int pingResponseTime) {
System.err.println("Ping: " + pingResponseTime);
PingTest.this.response = pingResponseTime;
stopEndPoints();
@ -137,7 +149,8 @@ public class PingTest extends BaseTest {
// alternate way to register for the receipt of a one-off ping response
// doesn't matter how many times this is called. If there is a PING waiting, then it's overwritten
Ping ping = client.send().ping();
Ping ping = client.send()
.ping();
ping.addListener(pingListener);
waitForThreads();
@ -149,7 +162,8 @@ public class PingTest extends BaseTest {
// ping prefers the following order: UDP, UDT, TCP
@Test
public void pingUDP() throws InitializationException, SecurityException {
public
void pingUDP() throws InitializationException, SecurityException, IOException {
this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -172,8 +186,10 @@ public class PingTest extends BaseTest {
client.connect(5000);
System.err.println("Testing UDP ping");
for (int i=0;i<10;i++) {
this.response = client.send().ping().getResponse();
for (int i = 0; i < 10; i++) {
this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response);
}
@ -187,7 +203,8 @@ public class PingTest extends BaseTest {
// ping prefers the following order: UDP, UDT, TCP
@Test
public void pingUDT() throws InitializationException, SecurityException {
public
void pingUDT() throws InitializationException, SecurityException, IOException {
this.response = -1;
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -209,8 +226,10 @@ public class PingTest extends BaseTest {
client.connect(5000);
System.err.println("Testing UDT ping");
for (int i=0;i<10;i++) {
this.response = client.send().ping().getResponse();
for (int i = 0; i < 10; i++) {
this.response = client.send()
.ping()
.getResponse();
System.err.println("Ping: " + this.response);
}

View File

@ -1,24 +1,25 @@
package dorkbox.network;
import static org.junit.Assert.assertEquals;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ReconnectTest extends BaseTest {
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public
class ReconnectTest extends BaseTest {
@Test
public void reconnect() throws InitializationException, SecurityException {
public
void reconnect() throws InitializationException, SecurityException, IOException {
final Timer timer = new Timer();
ConnectionOptions connectionOptions = new ConnectionOptions();
@ -30,18 +31,21 @@ public class ReconnectTest extends BaseTest {
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
server.listeners().add(new Listener<Object>() {
@Override
public void connected(final Connection connection) {
timer.schedule(new TimerTask() {
@Override
public void run () {
System.out.println("Disconnecting after 2 seconds.");
connection.close();
}
}, 2000);
}
});
server.listeners()
.add(new Listener<Object>() {
@Override
public
void connected(final Connection connection) {
timer.schedule(new TimerTask() {
@Override
public
void run() {
System.out.println("Disconnecting after 2 seconds.");
connection.close();
}
}, 2000);
}
});
// ----
@ -49,22 +53,25 @@ public class ReconnectTest extends BaseTest {
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<Object>() {
@Override
public void disconnected (Connection connection) {
if (reconnectCount.getAndIncrement() == 2) {
stopEndPoints();
return;
}
new Thread() {
@Override
public void run () {
System.out.println("Reconnecting: " + reconnectCount.get());
client.reconnect();
}
}.start();
}
});
client.listeners()
.add(new Listener<Object>() {
@Override
public
void disconnected(Connection connection) {
if (reconnectCount.getAndIncrement() == 2) {
stopEndPoints();
return;
}
new Thread() {
@Override
public
void run() {
System.out.println("Reconnecting: " + reconnectCount.get());
client.reconnect();
}
}.start();
}
});
client.connect(5000);
waitForThreads(10);

View File

@ -1,23 +1,27 @@
package dorkbox.network;
import java.lang.reflect.Method;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.util.exceptions.SecurityException;
import dorkbox.network.util.store.SettingsStore;
import dorkbox.util.SerializationManager;
import dorkbox.util.storage.Storage;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.crypto.params.ECPublicKeyParameters;
import org.junit.Test;
import dorkbox.network.util.exceptions.SecurityException;
import dorkbox.network.util.store.SettingsStore;
import java.io.IOException;
import java.lang.reflect.Method;
public class ReflectionSecurityTest extends BaseTest {
public
class ReflectionSecurityTest extends BaseTest {
private static boolean RUN_TEST = false;
@Test
public void directInvocation() {
public
void directInvocation() {
if (!RUN_TEST) {
System.out.println(" Not running test -- Skipping DirectInvocation test.");
// since we exit the JVM on failure, we only run the test in special test-cases, not every time.
@ -30,7 +34,8 @@ public class ReflectionSecurityTest extends BaseTest {
}
@Test
public void reflectionInvocationA() throws Exception {
public
void reflectionInvocationA() throws Exception {
if (!RUN_TEST) {
// since we exit the JVM on failure, we only run the test in special test-cases, not every time.
System.out.println(" Not running test -- Skipping ReflectionInvocationA test.");
@ -58,7 +63,8 @@ public class ReflectionSecurityTest extends BaseTest {
}
@Test
public void reflectionInvocationB() throws Exception {
public
void reflectionInvocationB() throws Exception {
if (!RUN_TEST) {
// since we exit the JVM on failure, we only run the test in special test-cases, not every time.
System.out.println(" Not running test -- Skipping ReflectionInvocationB test.");
@ -87,7 +93,8 @@ public class ReflectionSecurityTest extends BaseTest {
}
@Test
public void correctInvocation() throws SecurityException {
public
void correctInvocation() throws SecurityException {
SettingsStore connectionStore = new ConnectionTestStore();
connectionStore.getPrivateKey();
// if it's NOT successful, the JVM will shutdown!
@ -95,51 +102,68 @@ public class ReflectionSecurityTest extends BaseTest {
}
public static class ConnectionTestStore extends SettingsStore {
public static
class ConnectionTestStore extends SettingsStore {
@SuppressWarnings("unused")
private static SettingsStore create() throws SecurityException {
private static
SettingsStore create() throws SecurityException {
return new ConnectionTestStore();
}
@Override
public ECPrivateKeyParameters getPrivateKey() throws SecurityException {
public
void init(final Class<? extends EndPoint> type, final SerializationManager serializationManager, final Storage storage)
throws IOException {
}
@Override
public
ECPrivateKeyParameters getPrivateKey() throws SecurityException {
return null;
}
@Override
public void savePrivateKey(ECPrivateKeyParameters serverPrivateKey) throws SecurityException {
public
void savePrivateKey(ECPrivateKeyParameters serverPrivateKey) throws SecurityException {
}
@Override
public ECPublicKeyParameters getPublicKey() throws SecurityException {
public
ECPublicKeyParameters getPublicKey() throws SecurityException {
return null;
}
@Override
public void savePublicKey(ECPublicKeyParameters serverPublicKey) throws SecurityException {
public
void savePublicKey(ECPublicKeyParameters serverPublicKey) throws SecurityException {
}
@Override
public byte[] getSalt() {
public
byte[] getSalt() {
return null;
}
@Override
public ECPublicKeyParameters getRegisteredServerKey(byte[] hostAddress) throws SecurityException {
public
ECPublicKeyParameters getRegisteredServerKey(byte[] hostAddress) throws SecurityException {
return null;
}
@Override
public void addRegisteredServerKey(byte[] hostAddress, ECPublicKeyParameters publicKey) throws SecurityException {
public
void addRegisteredServerKey(byte[] hostAddress, ECPublicKeyParameters publicKey) throws SecurityException {
}
@Override
public boolean removeRegisteredServerKey(byte[] hostAddress) throws SecurityException {
public
boolean removeRegisteredServerKey(byte[] hostAddress) throws SecurityException {
return true;
}
@Override
public void shutdown() {
public
void shutdown() {
}
}
}

View File

@ -1,24 +1,25 @@
package dorkbox.network;
import static org.junit.Assert.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class ReuseTest extends BaseTest {
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.assertEquals;
public
class ReuseTest extends BaseTest {
AtomicInteger serverCount;
AtomicInteger clientCount;
@Test
public void socketReuse() throws InitializationException, SecurityException {
public
void socketReuse() throws InitializationException, SecurityException, IOException {
this.serverCount = new AtomicInteger(0);
this.clientCount = new AtomicInteger(0);
@ -30,45 +31,55 @@ public class ReuseTest extends BaseTest {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("-- TCP from server");
connection.send().UDP("-- UDP from server");
}
server.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("-- TCP from server");
connection.send()
.UDP("-- UDP from server");
}
@Override
public void received (Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
}
});
@Override
public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
}
});
// ----
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("-- TCP from client");
connection.send().UDP("-- UDP from client");
}
client.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("-- TCP from client");
connection.send()
.UDP("-- UDP from client");
}
@Override
public void received (Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
}
});
@Override
public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
}
});
server.bind(false);
int count = 10;
for (int i = 1; i < count+1; i++) {
for (int i = 1; i < count + 1; i++) {
client.connect(5000);
int target = i*2;
int target = i * 2;
while (this.serverCount.get() != target || this.clientCount.get() != target) {
System.err.println("Waiting...");
try {
@ -87,47 +98,56 @@ public class ReuseTest extends BaseTest {
}
@Test
public void localReuse() throws InitializationException, SecurityException {
public
void localReuse() throws InitializationException, SecurityException, IOException {
this.serverCount = new AtomicInteger(0);
this.clientCount = new AtomicInteger(0);
Server server = new Server();
server.disableRemoteKeyValidation();
addEndPoint(server);
server.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("-- LOCAL from server");
}
server.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("-- LOCAL from server");
}
@Override
public void received (Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
}
});
@Override
public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.serverCount.incrementAndGet();
System.err.println("<S " + connection + "> " + incrementAndGet + " : " + object);
}
});
// ----
Client client = new Client();
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners().add(new Listener<String>() {
@Override
public void connected (Connection connection) {
connection.send().TCP("-- LOCAL from client");
}
client.listeners()
.add(new Listener<String>() {
@Override
public
void connected(Connection connection) {
connection.send()
.TCP("-- LOCAL from client");
}
@Override
public void received (Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
}
});
@Override
public
void received(Connection connection, String object) {
int incrementAndGet = ReuseTest.this.clientCount.incrementAndGet();
System.err.println("<C " + connection + "> " + incrementAndGet + " : " + object);
}
});
server.bind(false);
int count = 10;
for (int i = 1; i < count+1; i++) {
for (int i = 1; i < count + 1; i++) {
client.connect(5000);
int target = i;

View File

@ -1,22 +1,23 @@
package dorkbox.network;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class UnregisteredClassTest extends BaseTest {
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.Assert.fail;
public
class UnregisteredClassTest extends BaseTest {
private String fail;
private int tries = 10000;
@ -24,7 +25,8 @@ public class UnregisteredClassTest extends BaseTest {
private AtomicInteger receivedUDP = new AtomicInteger();
@Test
public void unregisteredClasses() throws InitializationException, SecurityException {
public
void unregisteredClasses() throws InitializationException, SecurityException, IOException {
int origSize = EndPoint.udpMaxSize;
EndPoint.udpMaxSize = 2048;
@ -32,6 +34,7 @@ public class UnregisteredClassTest extends BaseTest {
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(false, false);
System.err.println("Running test " + this.tries + " times, please wait for it to finish.");
@ -42,94 +45,109 @@ public class UnregisteredClassTest extends BaseTest {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
server.getSerialization().setRegistrationRequired(false);
addEndPoint(server);
server.bind(false);
server.listeners().add(new Listener<Data>() {
@Override
public void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
}
server.listeners()
.add(new Listener<Data>() {
@Override
public
void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
}
@Override
public void received (Connection connection, Data data) {
if (data.isTCP) {
if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
connection.send().TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet();
} else {
if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
connection.send().UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet();
}
}
});
@Override
public
void received(Connection connection, Data data) {
if (data.isTCP) {
if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
connection.send()
.TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet();
}
else {
if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on server.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
connection.send()
.UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet();
}
}
});
// ----
Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
client.getSerialization().setRegistrationRequired(false);
addEndPoint(client);
client.listeners().add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false);
client.listeners()
.add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false);
@Override
public void connected (Connection connection) {
UnregisteredClassTest.this.fail = null;
connection.send().TCP(dataTCP);
connection.send().UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
}
@Override
public
void connected(Connection connection) {
UnregisteredClassTest.this.fail = null;
connection.send()
.TCP(dataTCP);
connection.send()
.UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
}
@Override
public void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
System.err.println(UnregisteredClassTest.this.fail);
}
@Override
public
void error(Connection connection, Throwable throwable) {
UnregisteredClassTest.this.fail = "Error during processing. " + throwable;
System.err.println(UnregisteredClassTest.this.fail);
}
@Override
public void received (Connection connection, Data data) {
if (data.isTCP) {
if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
if (this.checkTCP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send().TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet();
} else {
System.err.println("TCP done.");
this.doneTCP.set(true);
}
} else {
if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
if (this.checkUDP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send().UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet();
} else {
System.err.println("UDP done.");
this.doneUDP.set(true);
}
}
@Override
public
void received(Connection connection, Data data) {
if (data.isTCP) {
if (!data.equals(dataTCP)) {
UnregisteredClassTest.this.fail = "TCP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
if (this.checkTCP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send()
.TCP(data);
UnregisteredClassTest.this.receivedTCP.incrementAndGet();
}
else {
System.err.println("TCP done.");
this.doneTCP.set(true);
}
}
else {
if (!data.equals(dataUDP)) {
UnregisteredClassTest.this.fail = "UDP data is not equal on client.";
throw new RuntimeException("Fail! " + UnregisteredClassTest.this.fail);
}
if (this.checkUDP.getAndIncrement() <= UnregisteredClassTest.this.tries) {
connection.send()
.UDP(data);
UnregisteredClassTest.this.receivedUDP.incrementAndGet();
}
else {
System.err.println("UDP done.");
this.doneUDP.set(true);
}
}
if (this.doneTCP.get() && this.doneUDP.get()) {
System.err.println("Ran TCP & UDP " + UnregisteredClassTest.this.tries + " times each");
stopEndPoints();
}
}
});
if (this.doneTCP.get() && this.doneUDP.get()) {
System.err.println("Ran TCP & UDP " + UnregisteredClassTest.this.tries + " times each");
stopEndPoints();
}
}
});
client.connect(5000);
waitForThreads();
@ -141,7 +159,8 @@ public class UnregisteredClassTest extends BaseTest {
EndPoint.udpMaxSize = origSize;
}
private void populateData(Data data, boolean isTCP) {
private
void populateData(Data data, boolean isTCP) {
data.isTCP = isTCP;
StringBuilder buffer = new StringBuilder();
@ -153,8 +172,7 @@ public class UnregisteredClassTest extends BaseTest {
data.strings = new String[] {"ab012", "", null, "!@#$", "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>"};
data.ints = new int[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.shorts = new short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.floats = new float[] {0, -0, 1, -1, 123456, -123456, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE, Float.MIN_VALUE};
data.doubles = new double[] {0, -0, 1, -1, 123456, -123456, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.longs = new long[] {0, -0, 1, -1, 123456, -123456, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.bytes = new byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
@ -162,17 +180,17 @@ public class UnregisteredClassTest extends BaseTest {
data.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE};
data.Shorts = new Short[] {-12345, 12345, -1, 0, 1, Short.MAX_VALUE, Short.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float)Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE,
Double.MIN_VALUE};
data.Floats = new Float[] {0f, -0f, 1f, -1f, 123456f, -123456f, 0.1f, 0.2f, -0.3f, (float) Math.PI, Float.MAX_VALUE,
Float.MIN_VALUE};
data.Doubles = new Double[] {0d, -0d, 1d, -1d, 123456d, -123456d, 0.1d, 0.2d, -0.3d, Math.PI, Double.MAX_VALUE, Double.MIN_VALUE};
data.Longs = new Long[] {0l, -0l, 1l, -1l, 123456l, -123456l, 99999999999l, -99999999999l, Long.MAX_VALUE, Long.MIN_VALUE};
data.Bytes = new Byte[] {-123, 123, -1, 0, 1, Byte.MAX_VALUE, Byte.MIN_VALUE};
data.Chars = new Character[] {32345, 12345, 0, 1, 63, Character.MAX_VALUE, Character.MIN_VALUE};
data.Booleans = new Boolean[] {true, false};
}
static public class Data {
static public
class Data {
public String string;
public String[] strings;
public int[] ints;
@ -194,7 +212,8 @@ public class UnregisteredClassTest extends BaseTest {
public boolean isTCP;
@Override
public int hashCode () {
public
int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans);
@ -220,7 +239,8 @@ public class UnregisteredClassTest extends BaseTest {
}
@Override
public boolean equals (Object obj) {
public
boolean equals(Object obj) {
if (this == obj) {
return true;
}
@ -230,7 +250,7 @@ public class UnregisteredClassTest extends BaseTest {
if (getClass() != obj.getClass()) {
return false;
}
Data other = (Data)obj;
Data other = (Data) obj;
if (!Arrays.equals(this.Booleans, other.Booleans)) {
return false;
}
@ -286,7 +306,8 @@ public class UnregisteredClassTest extends BaseTest {
if (other.string != null) {
return false;
}
} else if (!this.string.equals(other.string)) {
}
else if (!this.string.equals(other.string)) {
return false;
}
if (!Arrays.equals(this.strings, other.strings)) {
@ -296,7 +317,8 @@ public class UnregisteredClassTest extends BaseTest {
}
@Override
public String toString () {
public
String toString() {
return "Data";
}
}

View File

@ -1,10 +1,5 @@
package dorkbox.network.rmi;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import dorkbox.network.BaseTest;
import dorkbox.network.Client;
import dorkbox.network.ConnectionOptions;
@ -12,11 +7,17 @@ import dorkbox.network.Server;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Test;
public class RmiSendObjectTest extends BaseTest {
import java.io.IOException;
import static org.junit.Assert.assertEquals;
public
class RmiSendObjectTest extends BaseTest {
private Rmi serverRMI;
/**
@ -24,7 +25,8 @@ public class RmiSendObjectTest extends BaseTest {
* uses the first remote object to get the second remote object.
*/
@Test
public void rmi() throws InitializationException, SecurityException {
public
void rmi() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
@ -32,7 +34,7 @@ public class RmiSendObjectTest extends BaseTest {
Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
SerializationManager serverSerializationManager = server.getSerialization();
ConnectionSerializationManager serverSerializationManager = server.getSerialization();
register(server, serverSerializationManager);
addEndPoint(server);
server.bind(false);
@ -40,7 +42,8 @@ public class RmiSendObjectTest extends BaseTest {
// After all common registrations, register OtherObjectImpl only on the server using the remote object interface ID.
// This causes OtherObjectImpl to be serialized as OtherObject.
int otherObjectID = serverSerializationManager.getRegistration(OtherObject.class).getId();
int otherObjectID = serverSerializationManager.getRegistration(OtherObject.class)
.getId();
serverSerializationManager.register(OtherObjectImpl.class, new RemoteObjectSerializer<OtherObjectImpl>(server), otherObjectID);
@ -53,15 +56,17 @@ public class RmiSendObjectTest extends BaseTest {
this.serverRMI.register(42, serverTestObject);
this.serverRMI.register(777, serverTestObject.getOtherObject());
server.listeners().add(new Listener<OtherObjectImpl>() {
@Override
public void received (Connection connection, OtherObjectImpl object) {
// The test is complete when the client sends the OtherObject instance.
if (object == serverTestObject.getOtherObject()) {
stopEndPoints();
}
}
});
server.listeners()
.add(new Listener<OtherObjectImpl>() {
@Override
public
void received(Connection connection, OtherObjectImpl object) {
// The test is complete when the client sends the OtherObject instance.
if (object == serverTestObject.getOtherObject()) {
stopEndPoints();
}
}
});
// ----
@ -70,69 +75,86 @@ public class RmiSendObjectTest extends BaseTest {
register(client, client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<Object>() {
@Override
public void connected(final Connection connection) {
new Thread(new Runnable() {
@Override
public void run() {
TestObject test = connection.getRemoteObject(42, TestObject.class);
// Normal remote method call.
assertEquals(43.21f, test.other(), .0001f);
client.listeners()
.add(new Listener<Object>() {
@Override
public
void connected(final Connection connection) {
new Thread(new Runnable() {
@Override
public
void run() {
TestObject test = connection.getRemoteObject(42, TestObject.class);
// Normal remote method call.
assertEquals(43.21f, test.other(), .0001f);
// Make a remote method call that returns another remote proxy object.
OtherObject otherObject = test.getOtherObject();
// Normal remote method call on the second object.
float value = otherObject.value();
assertEquals(12.34f, value, .0001f);
// Make a remote method call that returns another remote proxy object.
OtherObject otherObject = test.getOtherObject();
// Normal remote method call on the second object.
float value = otherObject.value();
assertEquals(12.34f, value, .0001f);
// When a remote proxy object is sent, the other side receives its actual remote object.
// we have to manually flush, since we are in a separate thread that does not auto-flush.
connection.send().TCP(otherObject).flush();
}
}).start();
}
});
// When a remote proxy object is sent, the other side receives its actual remote object.
// we have to manually flush, since we are in a separate thread that does not auto-flush.
connection.send()
.TCP(otherObject)
.flush();
}
}).start();
}
});
client.connect(5000);
waitForThreads(20);
}
/** Registers the same classes in the same order on both the client and server.
* @param server */
static public void register(EndPoint endpoint, SerializationManager kryoMT) {
/**
* Registers the same classes in the same order on both the client and server.
*/
public static
void register(EndPoint endpoint, ConnectionSerializationManager kryoMT) {
kryoMT.register(TestObject.class);
kryoMT.register(OtherObject.class, new RemoteObjectSerializer<OtherObject>(endpoint));
}
static public interface TestObject {
public float other();
public
interface TestObject {
float other();
public OtherObject getOtherObject();
OtherObject getOtherObject();
}
static public class TestObjectImpl implements TestObject {
public static
class TestObjectImpl implements TestObject {
public OtherObject otherObject;
@Override
public float other() {
public
float other() {
return 43.21f;
}
@Override
public OtherObject getOtherObject() {
public
OtherObject getOtherObject() {
return this.otherObject;
}
}
static public interface OtherObject {
public float value ();
public
interface OtherObject {
float value();
}
static public class OtherObjectImpl implements OtherObject {
public static
class OtherObjectImpl implements OtherObject {
@Override
public float value () {
public
float value() {
return 12.34f;
}
}

View File

@ -1,24 +1,26 @@
package dorkbox.network.rmi;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import dorkbox.network.BaseTest;
import dorkbox.network.Client;
import dorkbox.network.ConnectionOptions;
import dorkbox.network.Server;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener;
import dorkbox.network.util.SerializationManager;
import dorkbox.network.util.ConnectionSerializationManager;
import dorkbox.network.util.KryoConnectionSerializationManager;
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
import org.junit.Assert;
import org.junit.Test;
public class RmiTest extends BaseTest {
import java.io.IOException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public
class RmiTest extends BaseTest {
private static final int CLIENT_ID = 4321;
private static final int SERVER_ID = 1234;
@ -26,207 +28,16 @@ public class RmiTest extends BaseTest {
private static final int CLIENT_REMOTE_ID = 42;
private static final int SERVER_REMOTE_ID = 12;
@Test
public void rmi() throws InitializationException, SecurityException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
server.rmi().register(SERVER_REMOTE_ID, new TestObjectImpl(SERVER_ID));
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(SERVER_ID, m.testObject.id());
System.err.println("Client Finished!");
// normally this is in the 'connected', but we do it here, so that it's more linear and easier to debug
runTest(connection, CLIENT_REMOTE_ID, CLIENT_ID);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
// have to have this happen BEFORE any connections are made.
client.rmi().register(CLIENT_REMOTE_ID, new TestObjectImpl(CLIENT_ID));
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected (final Connection connection) {
RmiTest.runTest(connection, SERVER_REMOTE_ID, SERVER_ID);
}
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(CLIENT_ID, m.testObject.id());
System.err.println("Server Finished!");
stopEndPoints(2000);
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public void rmiMany() throws InitializationException, SecurityException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi().register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
assertEquals(256 + 512 + 1024, serverTestObject.moos);
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected (final Connection connection) {
new Thread() {
@Override
public void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
for (int i = 0; i < 256; i++) {
assertEquals(CLIENT_ID, test.id());
}
for (int i = 0; i < 256; i++) {
test.moo();
}
for (int i = 0; i < 256; i++) {
test.moo("" + i);
}
for (int i = 0; i < 256; i++) {
test.moo("" + i, 0);
}
connection.send().TCP(new MessageWithTestObject()).flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public void rmiSlow() throws InitializationException, SecurityException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
register(server.getSerialization());
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi().register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void received (Connection connection, MessageWithTestObject m) {
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
register(client.getSerialization());
addEndPoint(client);
client.listeners().add(new Listener<MessageWithTestObject>() {
@Override
public void connected(final Connection connection) {
new Thread() {
@Override
public void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
test.id();
// Timeout on purpose.
try {
((RemoteObject)test).setResponseTimeout(200);
test.slow();
Assert.fail();
} catch (TimeoutException ignored) {
}
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
}
((RemoteObject)test).setResponseTimeout(3000);
connection.send().TCP(new MessageWithTestObject()).flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
private static void runTest(final Connection connection, final int id, final int otherID) {
private static
void runTest(final Connection connection, final int id, final int otherID) {
new Thread() {
@Override
public void run () {
public
void run() {
System.err.println("Starting test for: " + id);
TestObject test = connection.getRemoteObject(id, TestObject.class);
RemoteObject remoteObject = (RemoteObject)test;
RemoteObject remoteObject = (RemoteObject) test;
// Default behavior. RMI is transparent, method calls behave like normal
// (return values and exceptions are returned, call is synchronous)
@ -254,7 +65,7 @@ public class RmiTest extends BaseTest {
boolean caught = false;
try {
test.throwException();
} catch(UnsupportedOperationException ex) {
} catch (UnsupportedOperationException ex) {
System.err.println("\tExpected.");
caught = true;
}
@ -268,7 +79,7 @@ public class RmiTest extends BaseTest {
caught = false;
try {
test.throwException();
} catch(UnsupportedOperationException ex) {
} catch (UnsupportedOperationException ex) {
caught = true;
}
assertTrue(caught);
@ -293,7 +104,8 @@ public class RmiTest extends BaseTest {
// Non-blocking call that errors out
remoteObject.setTransmitReturnValue(false);
test.throwException();
assertEquals(remoteObject.waitForLastResponse().getClass(), UnsupportedOperationException.class);
assertEquals(remoteObject.waitForLastResponse()
.getClass(), UnsupportedOperationException.class);
// Call will time out if non-blocking isn't working properly
remoteObject.setTransmitExceptions(false);
@ -304,12 +116,15 @@ public class RmiTest extends BaseTest {
m.number = 678;
m.text = "sometext";
m.testObject = connection.getRemoteObject(id, TestObject.class);
connection.send().TCP(m).flush();
connection.send()
.TCP(m)
.flush();
}
}.start();
}
static public void register (SerializationManager kryoMT) {
public static
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(Object.class); // Needed for Object#toString, hashCode, etc.
kryoMT.register(TestObject.class);
kryoMT.register(MessageWithTestObject.class);
@ -317,51 +132,279 @@ public class RmiTest extends BaseTest {
kryoMT.register(StackTraceElement[].class);
kryoMT.register(UnsupportedOperationException.class);
kryoMT.setReferences(true); // Needed for UnsupportedOperationException, which has a circular reference in the cause field.
}
public static interface TestObject {
public void throwException();
@Test
public
void rmi() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
public void moo();
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
public void moo(String value);
// have to have this happen BEFORE any connections are made.
server.rmi()
.register(SERVER_REMOTE_ID, new TestObjectImpl(SERVER_ID));
public void moo(String value, long delay);
server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(SERVER_ID, m.testObject.id());
System.err.println("Client Finished!");
public int id();
// normally this is in the 'connected', but we do it here, so that it's more linear and easier to debug
runTest(connection, CLIENT_REMOTE_ID, CLIENT_ID);
}
});
public float slow ();
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
// have to have this happen BEFORE any connections are made.
client.rmi()
.register(CLIENT_REMOTE_ID, new TestObjectImpl(CLIENT_ID));
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
RmiTest.runTest(connection, SERVER_REMOTE_ID, SERVER_ID);
}
@Override
public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(CLIENT_ID, m.testObject.id());
System.err.println("Server Finished!");
stopEndPoints(2000);
}
});
client.connect(5000);
waitForThreads(30);
}
public static class TestObjectImpl implements TestObject {
public long value = System.currentTimeMillis();
@Test
public
void rmiMany() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi()
.register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
assertEquals(256 + 512 + 1024, serverTestObject.moos);
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
new Thread() {
@Override
public
void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
for (int i = 0; i < 256; i++) {
assertEquals(CLIENT_ID, test.id());
}
for (int i = 0; i < 256; i++) {
test.moo();
}
for (int i = 0; i < 256; i++) {
test.moo("" + i);
}
for (int i = 0; i < 256; i++) {
test.moo("" + i, 0);
}
connection.send()
.TCP(new MessageWithTestObject())
.flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
@Test
public
void rmiSlow() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host;
connectionOptions.enableRmi = true;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT(true, true);
register(connectionOptions.serializationManager);
final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation();
addEndPoint(server);
server.bind(false);
// have to have this happen BEFORE any connections are made.
final TestObjectImpl serverTestObject = new TestObjectImpl(CLIENT_ID);
server.rmi()
.register(CLIENT_REMOTE_ID, serverTestObject);
server.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void received(Connection connection, MessageWithTestObject m) {
System.err.println("Client Finished!");
stopEndPoints(2000);
}
});
// ----
final Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation();
addEndPoint(client);
client.listeners()
.add(new Listener<MessageWithTestObject>() {
@Override
public
void connected(final Connection connection) {
new Thread() {
@Override
public
void run() {
TestObject test = connection.getRemoteObject(CLIENT_REMOTE_ID, TestObject.class);
test.id();
// Timeout on purpose.
try {
((RemoteObject) test).setResponseTimeout(200);
test.slow();
Assert.fail();
} catch (TimeoutException ignored) {
}
try {
Thread.sleep(300);
} catch (InterruptedException ignored) {
}
((RemoteObject) test).setResponseTimeout(3000);
connection.send()
.TCP(new MessageWithTestObject())
.flush();
}
}.start();
}
});
client.connect(5000);
waitForThreads(30);
}
public
interface TestObject {
void throwException();
void moo();
void moo(String value);
void moo(String value, long delay);
int id();
float slow();
}
public static
class TestObjectImpl implements TestObject {
private final int id;
public long value = System.currentTimeMillis();
public int moos;
public TestObjectImpl(int id) {
public
TestObjectImpl(int id) {
this.id = id;
}
@Override
public void throwException() {
public
void throwException() {
throw new UnsupportedOperationException("Why would I do that?");
}
@Override
public void moo() {
public
void moo() {
this.moos++;
System.out.println("Moo!");
}
@Override
public void moo(String value) {
public
void moo(String value) {
this.moos += 2;
System.out.println("Moo: " + value);
}
@Override
public void moo(String value, long delay) {
public
void moo(String value, long delay) {
this.moos += 4;
System.out.println("Moo: " + value + " (" + delay + ")");
try {
@ -372,21 +415,25 @@ public class RmiTest extends BaseTest {
}
@Override
public int id() {
public
int id() {
return this.id;
}
@Override
public float slow() {
public
float slow() {
try {
Thread.sleep(300);
} catch (InterruptedException ex) {
} catch (InterruptedException ignored) {
}
return 666;
}
}
public static class MessageWithTestObject implements RmiMessages {
public static
class MessageWithTestObject implements RmiMessages {
public int number;
public String text;
public TestObject testObject;