Network/not-fixed/SocketOpenTest.java

105 lines
2.7 KiB
Java
Executable File

/*
* Copyright 2018 dorkbox, llc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import dorkbox.network.connection.Connection;
import dorkbox.network.connection.Listener.OnConnected;
import dorkbox.util.exceptions.SecurityException;
/**
*
*/
public
class SocketOpenTest extends BaseTest {
CountDownLatch latch = new CountDownLatch(1);
@Test
public
void socketConnect() throws SecurityException {
Configuration configuration = new Configuration();
configuration.tcpPort = tcpPort;
configuration.host = host;
Server server = new Server(configuration);
addEndPoint(server);
server.listeners()
.add(new OnConnected<Connection>() {
@Override
public
void connected(final Connection connection) {
latch.countDown();
}
});
server.bind(false);
boolean connectedSocket = false;
// since we check the socket, if we are NOT connected to a socket, then we're done.
Socket sock = null;
try {
sock = new Socket(host, tcpPort);
if (sock.isConnected()) {
// connected to server
connectedSocket = true;
sock.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (sock != null) {
sock.close();
}
} catch (IOException ignored) {
}
}
Assert.assertTrue(connectedSocket);
Client client = new Client(configuration);
addEndPoint(client);
try {
client.connect(5000);
} catch (IOException e) {
e.printStackTrace();
}
try {
latch.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Assert.fail("Interrupted while waiting for latch...");
}
stopEndPoints();
waitForThreads(10);
}
}