为什么在serverSocket.accept()上什么也没发生?服务器从客户端获取数据,但程序对serverSocket.accept()方法不执行任何操作
public void start() {
try {
Socket socket= serverSocket.accept();
System.out.println("Client accepted");
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
try {
line = in.readUTF();
System.out.println(line);
} catch (IOException i) {
System.out.println(i);
}
} catch (IOException e) {
System.out.println(e);
}
}
答案 0 :(得分:2)
serverSocket.accept();
阻塞,直到连接了套接字。
Socket s = serverSocket.accept();
in = new DataInputStream(new BufferedInputStream(s.getInputStream()));
OR
socket = serverSocket.accept();
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
编辑-29.03.2019 11.54
所以我们知道:
serverSocket.accept();
阻止您的线程。您可以在主线程中调用它。
...
successfulThreads = new AtomicInteger(0);
latch = new CountDownLatch(testcaseThreads);
gate = new CyclicBarrier(testcaseThreads + 1);
server = new Server(SOCKET_PORT);
server.start(); //<-- Your program blocks!!!
// ||
// || STOP! No execution of the code.
// \\//
// \/
for (File testcaseFile : testcaseFiles) {
new Thread(new MockClient(this, testcaseFile)).start();
}