-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
TcpServer.java
83 lines (71 loc) · 2.32 KB
/
TcpServer.java
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package io.dropwizard.logging;
import org.junit.rules.ExternalResource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.CountDownLatch;
import static org.assertj.core.api.Assertions.assertThat;
class TcpServer extends ExternalResource {
private final Thread thread;
private final ServerSocket serverSocket;
private final int messageCount = 100;
private final CountDownLatch latch = new CountDownLatch(messageCount);
TcpServer(ServerSocket serverSocket) {
this.serverSocket = serverSocket;
thread = new Thread(() -> {
while (!Thread.currentThread().isInterrupted()) {
Socket socket;
try {
socket = serverSocket.accept();
} catch (SocketException e) {
break;
} catch (IOException e) {
e.printStackTrace();
continue;
}
new Thread(() -> readAndVerifyData(socket)).start();
}
});
}
ServerSocket getServerSocket() {
return serverSocket;
}
int getMessageCount() {
return messageCount;
}
CountDownLatch getLatch() {
return latch;
}
@Override
protected void before() throws Throwable {
thread.start();
}
@Override
protected void after() {
thread.interrupt();
try {
serverSocket.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
private void readAndVerifyData(Socket socket) {
try (Socket s = socket; BufferedReader reader = new BufferedReader(new InputStreamReader(
s.getInputStream(), StandardCharsets.UTF_8))) {
for (int i = 0; i < messageCount; i++) {
String line = reader.readLine();
if (line == null) {
break;
}
assertThat(line).startsWith("INFO").contains("com.example.app: Application log " + i);
latch.countDown();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}