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

View File

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

View File

@ -1,58 +1,66 @@
package dorkbox.network; 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.Connection;
import dorkbox.network.connection.Listener; 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.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; 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); private AtomicBoolean checkPassed = new AtomicBoolean(false);
@Test @Test
public void sendDataFromClientClass () throws InitializationException, SecurityException { public
void sendDataFromClientClass() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
register(server.getSerialization());
server.listeners().add(new Listener<AMessage>() { server.listeners()
@Override .add(new Listener<AMessage>() {
public void received (Connection connection, AMessage object) { @Override
System.err.println("Server received message from client. Bouncing back."); public
connection.send().TCP(object); 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 client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
register(client.getSerialization());
client.connect(5000); client.connect(5000);
client.listeners().add(new Listener<AMessage>() { client.listeners()
@Override .add(new Listener<AMessage>() {
public void received (Connection connection, AMessage object) { @Override
ClientSendTest.this.checkPassed.set(true); public
stopEndPoints(); void received(Connection connection, AMessage object) {
} ClientSendTest.this.checkPassed.set(true);
}); stopEndPoints();
}
});
client.send().TCP(new AMessage()); client.send()
.TCP(new AMessage());
waitForThreads(); 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); kryoMT.register(AMessage.class);
} }
public static class AMessage { public static
public AMessage () { class AMessage {
public
AMessage() {
} }
} }
} }

View File

@ -1,161 +1,187 @@
package dorkbox.network; 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.Timer;
import java.util.TimerTask; import java.util.TimerTask;
import org.junit.Test; public
class ConnectionTest extends BaseTest {
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 {
@Test @Test
public void connectLocal() throws InitializationException, SecurityException { public
void connectLocal() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "Local"); 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); waitForThreads(10);
} }
@Test @Test
public void connectTcp() throws InitializationException, SecurityException { public
void connectTcp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP"); System.out.println("---- " + "TCP");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; 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; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdp() throws InitializationException, SecurityException { public
void connectTcpUdp() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP"); System.out.println("---- " + "TCP UDP");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; 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; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdt() throws InitializationException, SecurityException { public
void connectTcpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDT"); System.out.println("---- " + "TCP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udtPort = udtPort; 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; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
@Test @Test
public void connectTcpUdpUdt() throws InitializationException, SecurityException { public
void connectTcpUdpUdt() throws InitializationException, SecurityException, IOException {
System.out.println("---- " + "TCP UDP UDT"); System.out.println("---- " + "TCP UDP UDT");
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort; 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; connectionOptions.host = host;
startClient(connectionOptions); startClient(connectionOptions);
server.waitForStop(true);
waitForThreads(10); waitForThreads(10);
} }
private Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException { private
Server server; Server startServer(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
if (connectionOptions != null) { Server server = new Server(connectionOptions);
server = new Server(connectionOptions);
} else {
server = new Server();
}
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
server.bind(false);
server.listeners().add(new Listener<Object>() {
Timer timer = new Timer();
@Override server.bind(false);
public void connected (final Connection connection) { server.listeners()
this.timer.schedule(new TimerTask() { .add(new Listener<Object>() {
@Override Timer timer = new Timer();
public void run () {
System.out.println("Disconnecting after 1 second."); @Override
connection.close(); public
} void connected(final Connection connection) {
}, 1000); 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; return server;
} }
private Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException { private
Client startClient(ConnectionOptions connectionOptions) throws InitializationException, SecurityException, IOException {
Client client; Client client;
if (connectionOptions != null) { if (connectionOptions != null) {
client = new Client(connectionOptions); client = new Client(connectionOptions);
} else { }
else {
client = new Client(); client = new Client();
} }
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
@Override .add(new Listener<Object>() {
public void disconnected(Connection connection) { @Override
stopEndPoints(); public
} void disconnected(Connection connection) {
}); stopEndPoints();
}
});
client.connect(5000); client.connect(5000);
client.send()
.TCP(new BMessage())
.flush();
return client; 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; package dorkbox.network;
import static org.junit.Assert.fail;
import org.junit.Test;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; import dorkbox.network.connection.Listener;
import dorkbox.network.util.exceptions.InitializationException; import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; 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; volatile boolean connected = false;
@Test @Test
public void broadcast () throws InitializationException, SecurityException { public
void broadcast() throws InitializationException, SecurityException, IOException {
ConnectionOptions connectionOptions = new ConnectionOptions(); ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
@ -39,13 +41,15 @@ public class DiscoverHostTest extends BaseTest {
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<Object>() { client.listeners()
@Override .add(new Listener<Object>() {
public void connected(Connection connection) { @Override
DiscoverHostTest.this.connected = true; public
stopEndPoints(); void connected(Connection connection) {
} DiscoverHostTest.this.connected = true;
}); stopEndPoints();
}
});
client.connect(2000); client.connect(2000);
waitForThreads(2); waitForThreads(2);

View File

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

View File

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

View File

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

View File

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

View File

@ -1,23 +1,24 @@
package dorkbox.network; 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.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Test; import static org.junit.Assert.assertEquals;
import dorkbox.network.connection.Connection; public
import dorkbox.network.connection.Listener; class MultipleThreadTest extends BaseTest {
import dorkbox.network.util.exceptions.InitializationException;
import dorkbox.network.util.exceptions.SecurityException;
public class MultipleThreadTest extends BaseTest {
AtomicInteger sent = new AtomicInteger(0); AtomicInteger sent = new AtomicInteger(0);
AtomicInteger totalClientCounter = new AtomicInteger(1); AtomicInteger totalClientCounter = new AtomicInteger(1);
AtomicInteger receivedServer = 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 threadCount = 15;
private final int clientCount = 13; 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 @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 connectionOptions = new ConnectionOptions();
connectionOptions.tcpPort = tcpPort; connectionOptions.tcpPort = tcpPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = serializationManager;
final Server server = new Server(connectionOptions); final Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
server.getSerialization().register(String[].class);
server.getSerialization().register(DataClass.class);
addEndPoint(server); addEndPoint(server);
server.bind(false); server.bind(false);
server.listeners().add(new Listener<DataClass>() { server.listeners()
@Override .add(new Listener<DataClass>() {
public void connected(final Connection connection) { @Override
System.err.println("Client connected to server."); 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. // kickoff however many threads we need, and send data to the client.
for (int i = 1; i <= MultipleThreadTest.this.threadCount; i++) { for (int i = 1; i <= MultipleThreadTest.this.threadCount; i++) {
final int index = i; final int index = i;
new Thread() { new Thread() {
@Override @Override
public void run () { public
for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) { void run() {
int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement(); for (int i = 1; i <= MultipleThreadTest.this.messageCount; i++) {
DataClass dataClass = new DataClass("Server -> client. Thread #" + index + " message# " + incrementAndGet, incrementAndGet); int incrementAndGet = MultipleThreadTest.this.sent.getAndIncrement();
MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass); DataClass dataClass = new DataClass(
connection.send().TCP(dataClass).flush(); "Server -> client. Thread #" + index + " message# " + incrementAndGet,
} incrementAndGet);
} MultipleThreadTest.this.sentStringsToClientDebug.put(incrementAndGet, dataClass);
}.start(); connection.send()
} .TCP(dataClass)
} .flush();
}
}
}.start();
}
}
@Override @Override
public void received (Connection connection, DataClass object) { public
int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement(); void received(Connection connection, DataClass object) {
int incrementAndGet = MultipleThreadTest.this.receivedServer.getAndIncrement();
if (incrementAndGet == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.clientCount) { if (incrementAndGet == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.clientCount) {
System.err.println("Server DONE " + incrementAndGet); System.err.println("Server DONE " + incrementAndGet);
// note. this is getting called BEFORE it's ready? // note. this is getting called BEFORE it's ready?
stopEndPoints(); stopEndPoints();
synchronized (MultipleThreadTest.this.lock) { synchronized (MultipleThreadTest.this.lock) {
MultipleThreadTest.this.lock.notifyAll(); MultipleThreadTest.this.lock.notifyAll();
} }
} }
} }
}); });
// ---- // ----
@ -94,32 +107,37 @@ public class MultipleThreadTest extends BaseTest {
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
this.clients.add(client); this.clients.add(client);
client.getSerialization().register(String[].class);
client.getSerialization().register(DataClass.class);
addEndPoint(client); addEndPoint(client);
client.listeners().add(new Listener<DataClass>() { client.listeners()
AtomicInteger received = new AtomicInteger(1); .add(new Listener<DataClass>() {
AtomicInteger received = new AtomicInteger(1);
@Override @Override
public void connected(Connection connection) { public
System.err.println("Client #" + index + " connected."); void connected(Connection connection) {
} System.err.println("Client #" + index + " connected.");
}
@Override @Override
public void received (Connection connection, DataClass object) { public
int clientLocalCounter = this.received.getAndIncrement(); void received(Connection connection, DataClass object) {
MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index); int clientLocalCounter = this.received.getAndIncrement();
MultipleThreadTest.this.sentStringsToClientDebug.remove(object.index);
// we finished!! // we finished!!
if (clientLocalCounter == MultipleThreadTest.this.messageCount * MultipleThreadTest.this.threadCount) { 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."); System.err.println("Client #" + index + " received " + clientLocalCounter + " (" +
// now spam back messages! MultipleThreadTest.this.totalClientCounter.getAndIncrement() + ") Sending back " +
for (int i = 0; i < MultipleThreadTest.this.messageCount; i++) { MultipleThreadTest.this.messageCount + " messages.");
connection.send().TCP(new DataClass("Client #" + index + " -> Server message " + i, index)); // 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); 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. // 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 // 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) { synchronized (this.lock) {
try { try {
@ -145,17 +164,20 @@ public class MultipleThreadTest extends BaseTest {
} }
stopEndPoints(); 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 String data;
public Integer index; public Integer index;
public DataClass() { public
DataClass() {
} }
public DataClass(String data, Integer index) { public
DataClass(String data, Integer index) {
this.data = data; this.data = data;
this.index = index; this.index = index;
} }

View File

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

View File

@ -1,33 +1,36 @@
package dorkbox.network; 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.Connection;
import dorkbox.network.connection.EndPoint; import dorkbox.network.connection.EndPoint;
import dorkbox.network.connection.Listener; 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.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; 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; private volatile String fail;
int tries = 1000; int tries = 1000;
enum TYPE { enum TYPE {
TCP, UDP, UDT TCP, UDP, UDT
} }
@Test @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. // UDP data is kinda big. Make sure it fits into one packet.
int origSize = EndPoint.udpMaxSize; int origSize = EndPoint.udpMaxSize;
EndPoint.udpMaxSize = 2048; EndPoint.udpMaxSize = 2048;
@ -39,6 +42,8 @@ public class PingPongTest extends BaseTest {
connectionOptions.udpPort = udpPort; connectionOptions.udpPort = udpPort;
connectionOptions.udtPort = udtPort; connectionOptions.udtPort = udtPort;
connectionOptions.host = host; connectionOptions.host = host;
connectionOptions.serializationManager = KryoConnectionSerializationManager.DEFAULT();
register(connectionOptions.serializationManager);
final Data dataTCP = new Data(); final Data dataTCP = new Data();
populateData(dataTCP, TYPE.TCP); populateData(dataTCP, TYPE.TCP);
@ -50,118 +55,138 @@ public class PingPongTest extends BaseTest {
Server server = new Server(connectionOptions); Server server = new Server(connectionOptions);
server.disableRemoteKeyValidation(); server.disableRemoteKeyValidation();
addEndPoint(server); addEndPoint(server);
register(server.getSerialization());
server.bind(false); server.bind(false);
server.listeners().add(new Listener<Data>() { server.listeners()
@Override .add(new Listener<Data>() {
public void error(Connection connection, Throwable throwable) { @Override
PingPongTest.this.fail = "Error during processing. " + throwable; public
} void error(Connection connection, Throwable throwable) {
PingPongTest.this.fail = "Error during processing. " + throwable;
}
@Override @Override
public void received (Connection connection, Data data) { public
if (data.type == TYPE.TCP) { void received(Connection connection, Data data) {
if (!data.equals(dataTCP)) { if (data.type == TYPE.TCP) {
PingPongTest.this.fail = "TCP data is not equal on server."; if (!data.equals(dataTCP)) {
throw new RuntimeException("Fail! " + PingPongTest.this.fail); PingPongTest.this.fail = "TCP data is not equal on server.";
} throw new RuntimeException("Fail! " + PingPongTest.this.fail);
connection.send().TCP(data); }
} connection.send()
else if (data.type == TYPE.UDP) { .TCP(data);
if (!data.equals(dataUDP)) { }
PingPongTest.this.fail = "UDP data is not equal on server."; else if (data.type == TYPE.UDP) {
throw new RuntimeException("Fail! " + PingPongTest.this.fail); if (!data.equals(dataUDP)) {
} PingPongTest.this.fail = "UDP data is not equal on server.";
connection.send().UDP(data); throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} }
else if (data.type == TYPE.UDT) { connection.send()
if (!data.equals(dataUDT)) { .UDP(data);
PingPongTest.this.fail = "UDT data is not equal on server."; }
throw new RuntimeException("Fail! " + PingPongTest.this.fail); else if (data.type == TYPE.UDT) {
} if (!data.equals(dataUDT)) {
connection.send().UDT(data); PingPongTest.this.fail = "UDT data is not equal on server.";
} throw new RuntimeException("Fail! " + PingPongTest.this.fail);
else { }
PingPongTest.this.fail = "Unknown data type on server."; connection.send()
throw new RuntimeException("Fail! " + PingPongTest.this.fail); .UDT(data);
} }
} else {
}); PingPongTest.this.fail = "Unknown data type on server.";
throw new RuntimeException("Fail! " + PingPongTest.this.fail);
}
}
});
// ---- // ----
Client client = new Client(connectionOptions); Client client = new Client(connectionOptions);
client.disableRemoteKeyValidation(); client.disableRemoteKeyValidation();
addEndPoint(client); addEndPoint(client);
register(client.getSerialization()); client.listeners()
client.listeners().add(new Listener<Data>() { .add(new Listener<Data>() {
AtomicInteger checkTCP = new AtomicInteger(0); AtomicInteger checkTCP = new AtomicInteger(0);
AtomicInteger checkUDP = new AtomicInteger(0); AtomicInteger checkUDP = new AtomicInteger(0);
AtomicInteger checkUDT = new AtomicInteger(0); AtomicInteger checkUDT = new AtomicInteger(0);
AtomicBoolean doneTCP = new AtomicBoolean(false); AtomicBoolean doneTCP = new AtomicBoolean(false);
AtomicBoolean doneUDP = new AtomicBoolean(false); AtomicBoolean doneUDP = new AtomicBoolean(false);
AtomicBoolean doneUDT = new AtomicBoolean(false); AtomicBoolean doneUDT = new AtomicBoolean(false);
@Override @Override
public void connected (Connection connection) { public
PingPongTest.this.fail = null; void connected(Connection connection) {
connection.send().TCP(dataTCP); PingPongTest.this.fail = null;
connection.send().UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost. connection.send()
connection.send().UDT(dataUDT); .TCP(dataTCP);
} connection.send()
.UDP(dataUDP); // UDP ping pong stops if a UDP packet is lost.
connection.send()
.UDT(dataUDT);
}
@Override @Override
public void error(Connection connection, Throwable throwable) { public
PingPongTest.this.fail = "Error during processing. " + throwable; void error(Connection connection, Throwable throwable) {
throwable.printStackTrace(); PingPongTest.this.fail = "Error during processing. " + throwable;
} throwable.printStackTrace();
}
@Override @Override
public void received (Connection connection, Data data) { public
if (data.type == TYPE.TCP) { void received(Connection connection, Data data) {
if (!data.equals(dataTCP)) { if (data.type == TYPE.TCP) {
PingPongTest.this.fail = "TCP data is not equal on client."; if (!data.equals(dataTCP)) {
throw new RuntimeException("Fail! " + PingPongTest.this.fail); 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); if (this.checkTCP.getAndIncrement() <= PingPongTest.this.tries) {
} else { connection.send()
System.err.println("TCP done."); .TCP(data);
this.doneTCP.set(true); }
} else {
} else if (data.type == TYPE.UDP) { System.err.println("TCP done.");
if (!data.equals(dataUDP)) { this.doneTCP.set(true);
PingPongTest.this.fail = "UDP data is not equal on client."; }
throw new RuntimeException("Fail! " + PingPongTest.this.fail); }
} else if (data.type == TYPE.UDP) {
if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) { if (!data.equals(dataUDP)) {
connection.send().UDP(data); PingPongTest.this.fail = "UDP data is not equal on client.";
} else { throw new RuntimeException("Fail! " + PingPongTest.this.fail);
System.err.println("UDP done."); }
this.doneUDP.set(true); if (this.checkUDP.getAndIncrement() <= PingPongTest.this.tries) {
} connection.send()
} else if (data.type == TYPE.UDT) { .UDP(data);
if (!data.equals(dataUDT)) { }
PingPongTest.this.fail = "UDT data is not equal on client."; else {
throw new RuntimeException("Fail! " + PingPongTest.this.fail); System.err.println("UDP done.");
} this.doneUDP.set(true);
if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) { }
connection.send().UDT(data); }
} else { else if (data.type == TYPE.UDT) {
System.err.println("UDT done."); if (!data.equals(dataUDT)) {
this.doneUDT.set(true); PingPongTest.this.fail = "UDT data is not equal on client.";
} throw new RuntimeException("Fail! " + PingPongTest.this.fail);
} else { }
PingPongTest.this.fail = "Unknown data type on client."; if (this.checkUDT.getAndIncrement() <= PingPongTest.this.tries) {
throw new RuntimeException("Fail! " + PingPongTest.this.fail); 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()) { if (this.doneTCP.get() && this.doneUDP.get() && this.doneUDT.get()) {
System.err.println("Ran TCP, UDP, UDT " + PingPongTest.this.tries + " times each"); System.err.println("Ran TCP, UDP, UDT " + PingPongTest.this.tries + " times each");
stopEndPoints(); stopEndPoints();
} }
} }
}); });
client.connect(5000); client.connect(5000);
@ -174,7 +199,8 @@ public class PingPongTest extends BaseTest {
EndPoint.udpMaxSize = origSize; EndPoint.udpMaxSize = origSize;
} }
private void populateData (Data data, TYPE type) { private
void populateData(Data data, TYPE type) {
data.type = type; data.type = type;
StringBuilder buffer = new StringBuilder(); 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.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.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.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.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.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.booleans = new boolean[] {true, false};
data.Ints = new Integer[] {-1234567, 1234567, -1, 0, 1, Integer.MAX_VALUE, Integer.MIN_VALUE}; 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.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.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.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.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}; data.Booleans = new Boolean[] {true, false};
} }
private void register (SerializationManager kryoMT) { private
void register(ConnectionSerializationManager kryoMT) {
kryoMT.register(int[].class); kryoMT.register(int[].class);
kryoMT.register(short[].class); kryoMT.register(short[].class);
kryoMT.register(float[].class); kryoMT.register(float[].class);
@ -226,7 +254,8 @@ public class PingPongTest extends BaseTest {
kryoMT.register(TYPE.class); kryoMT.register(TYPE.class);
} }
static public class Data { static public
class Data {
public TYPE type; public TYPE type;
public String string; public String string;
public String[] strings; public String[] strings;
@ -249,7 +278,8 @@ public class PingPongTest extends BaseTest {
@Override @Override
public int hashCode() { public
int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + Arrays.hashCode(this.Booleans); result = prime * result + Arrays.hashCode(this.Booleans);
@ -275,7 +305,8 @@ public class PingPongTest extends BaseTest {
} }
@Override @Override
public boolean equals(Object obj) { public
boolean equals(Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
@ -338,7 +369,8 @@ public class PingPongTest extends BaseTest {
if (other.string != null) { if (other.string != null) {
return false; return false;
} }
} else if (!this.string.equals(other.string)) { }
else if (!this.string.equals(other.string)) {
return false; return false;
} }
if (!Arrays.equals(this.strings, other.strings)) { if (!Arrays.equals(this.strings, other.strings)) {
@ -351,7 +383,8 @@ public class PingPongTest extends BaseTest {
} }
@Override @Override
public String toString () { public
String toString() {
return "Data"; return "Data";
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,24 +1,26 @@
package dorkbox.network.rmi; 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.BaseTest;
import dorkbox.network.Client; import dorkbox.network.Client;
import dorkbox.network.ConnectionOptions; import dorkbox.network.ConnectionOptions;
import dorkbox.network.Server; import dorkbox.network.Server;
import dorkbox.network.connection.Connection; import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener; 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.InitializationException;
import dorkbox.network.util.exceptions.SecurityException; 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 CLIENT_ID = 4321;
private static final int SERVER_ID = 1234; 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 CLIENT_REMOTE_ID = 42;
private static final int SERVER_REMOTE_ID = 12; private static final int SERVER_REMOTE_ID = 12;
@Test private static
public void rmi() throws InitializationException, SecurityException { void runTest(final Connection connection, final int id, final int otherID) {
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) {
new Thread() { new Thread() {
@Override @Override
public void run () { public
void run() {
System.err.println("Starting test for: " + id); System.err.println("Starting test for: " + id);
TestObject test = connection.getRemoteObject(id, TestObject.class); 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 // Default behavior. RMI is transparent, method calls behave like normal
// (return values and exceptions are returned, call is synchronous) // (return values and exceptions are returned, call is synchronous)
@ -254,7 +65,7 @@ public class RmiTest extends BaseTest {
boolean caught = false; boolean caught = false;
try { try {
test.throwException(); test.throwException();
} catch(UnsupportedOperationException ex) { } catch (UnsupportedOperationException ex) {
System.err.println("\tExpected."); System.err.println("\tExpected.");
caught = true; caught = true;
} }
@ -268,7 +79,7 @@ public class RmiTest extends BaseTest {
caught = false; caught = false;
try { try {
test.throwException(); test.throwException();
} catch(UnsupportedOperationException ex) { } catch (UnsupportedOperationException ex) {
caught = true; caught = true;
} }
assertTrue(caught); assertTrue(caught);
@ -293,7 +104,8 @@ public class RmiTest extends BaseTest {
// Non-blocking call that errors out // Non-blocking call that errors out
remoteObject.setTransmitReturnValue(false); remoteObject.setTransmitReturnValue(false);
test.throwException(); 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 // Call will time out if non-blocking isn't working properly
remoteObject.setTransmitExceptions(false); remoteObject.setTransmitExceptions(false);
@ -304,12 +116,15 @@ public class RmiTest extends BaseTest {
m.number = 678; m.number = 678;
m.text = "sometext"; m.text = "sometext";
m.testObject = connection.getRemoteObject(id, TestObject.class); m.testObject = connection.getRemoteObject(id, TestObject.class);
connection.send().TCP(m).flush(); connection.send()
.TCP(m)
.flush();
} }
}.start(); }.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(Object.class); // Needed for Object#toString, hashCode, etc.
kryoMT.register(TestObject.class); kryoMT.register(TestObject.class);
kryoMT.register(MessageWithTestObject.class); kryoMT.register(MessageWithTestObject.class);
@ -317,51 +132,279 @@ public class RmiTest extends BaseTest {
kryoMT.register(StackTraceElement[].class); kryoMT.register(StackTraceElement[].class);
kryoMT.register(UnsupportedOperationException.class); kryoMT.register(UnsupportedOperationException.class);
kryoMT.setReferences(true); // Needed for UnsupportedOperationException, which has a circular reference in the cause field.
} }
public static interface TestObject { @Test
public void throwException(); 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 { @Test
public long value = System.currentTimeMillis(); 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; private final int id;
public long value = System.currentTimeMillis();
public int moos; public int moos;
public TestObjectImpl(int id) { public
TestObjectImpl(int id) {
this.id = id; this.id = id;
} }
@Override @Override
public void throwException() { public
void throwException() {
throw new UnsupportedOperationException("Why would I do that?"); throw new UnsupportedOperationException("Why would I do that?");
} }
@Override @Override
public void moo() { public
void moo() {
this.moos++; this.moos++;
System.out.println("Moo!"); System.out.println("Moo!");
} }
@Override @Override
public void moo(String value) { public
void moo(String value) {
this.moos += 2; this.moos += 2;
System.out.println("Moo: " + value); System.out.println("Moo: " + value);
} }
@Override @Override
public void moo(String value, long delay) { public
void moo(String value, long delay) {
this.moos += 4; this.moos += 4;
System.out.println("Moo: " + value + " (" + delay + ")"); System.out.println("Moo: " + value + " (" + delay + ")");
try { try {
@ -372,21 +415,25 @@ public class RmiTest extends BaseTest {
} }
@Override @Override
public int id() { public
int id() {
return this.id; return this.id;
} }
@Override @Override
public float slow() { public
float slow() {
try { try {
Thread.sleep(300); Thread.sleep(300);
} catch (InterruptedException ex) { } catch (InterruptedException ignored) {
} }
return 666; return 666;
} }
} }
public static class MessageWithTestObject implements RmiMessages {
public static
class MessageWithTestObject implements RmiMessages {
public int number; public int number;
public String text; public String text;
public TestObject testObject; public TestObject testObject;