相關代碼:
@Test
public void serverTest() throws IOException {
GameServer server = new GameServer();
server.start(9000);
GameClient client1 = new GameClient();
GameClient client2 = new GameClient();
client1.startConnection("localhost", 9000);
client2.startConnection("localhost", 9000);
client1.sendMessage("Hey I am client 1");
client2.sendMessage("Hey I am client 2");
}
public class GameServer {
private ServerSocket serverSocket;
public void start(int port) throws IOException {
System.out.println("Server started !!!");
serverSocket = new ServerSocket(port);
while (true) {
new Thread(new GameClientHandler(serverSocket.accept())).start();
}
}
public void stop() throws IOException {
serverSocket.close();
}
private static class GameClientHandler implements Runnable {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public GameClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String inputLine = in.readLine();
while ((inputLine = in.readLine()) != null){
System.out.print(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
out.close();
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Why can't the server and client be started together in the @Test? I think it gets stuck in the infinite while loop but at the same time, shouldn't there be context switching with the new threads started after accepting the connection?
I expected at least the name of the 2 new threads to be printed but it doesn't happen.
uj5u.com熱心網友回復:
讓我們仔細查看您的測驗代碼:
GameServer server = new GameServer();
好的,這一行創建了一個服務器,測驗執行緒準備好執行下一行
server.start(9000);
好的,測驗執行緒啟動服務器,并準備在start方法回傳時執行下一行。
發生了什么start:
System.out.println("Server started !!!");
好的,您應該會看到該訊息
serverSocket = new ServerSocket(port);
好的,你已經創建了一個 ServerSocket
while (true) {
new Thread(new GameClientHandler(serverSocket.accept())).start();
}
好的,您等待連接(at serverSocket.accept()),一旦您獲得連接,就會創建一個新執行緒來處理它,然后再次回圈。
但此時,測驗執行緒正在等待,永遠不會去下一行開始第一個連接。除非有其他東西(可能是另一個執行緒)啟動那些該死的連接,否則它會一直卡住。
uj5u.com熱心網友回復:
該方法GameServer.start只會回傳例外。那是因為你有 while 回圈。
因此,您的測驗執行將啟動服務器并等待有人打開連接,但這從未發生過。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359326.html
上一篇:條件變數 互斥鎖 pthreads的C 生產者消費者問題
下一篇:異步執行緒在TPL等待時死亡
