blob: 97b6bc086628daa86d4081d0e70a32265ba574ce (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
package org.gnunet.testing;
import org.gnunet.util.Client;
import org.gnunet.util.RelativeTime;
import org.gnunet.util.Server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.ServerSocketChannel;
/**
* Server with an ephemeral port.
* Can spawn clients connected to the server for testing.
*
* @author Florian Dold
*/
public class TestingServer {
public final Server server;
private final ServerSocketChannel srvChan;
public TestingServer() {
this(RelativeTime.FOREVER, true);
}
public TestingServer(RelativeTime idleTimeout, boolean requireFound) {
try {
srvChan = ServerSocketChannel.open();
srvChan.configureBlocking(false);
// bind to ephemeral port
srvChan.socket().bind(null);
} catch (IOException e) {
throw new RuntimeException("TestingServer creation failed");
}
server = new Server(idleTimeout, requireFound);
server.addAcceptSocket(srvChan);
}
/**
* Create a client connected to this server.
*
* @return a client connected to this server
*/
public Client createClient() {
SocketAddress socketAddress = srvChan.socket().getLocalSocketAddress();
if (!(socketAddress instanceof InetSocketAddress)) {
throw new RuntimeException("unknown type of socket address");
}
InetSocketAddress saddr = (InetSocketAddress) socketAddress;
String hostname = saddr.getHostName();
if (hostname == null) {
throw new RuntimeException("localhost SocketAddress has no hostname");
}
return new Client(hostname, srvChan.socket().getLocalPort());
}
}
|