我測試了本地機器上的套接字。我試圖在一個程序中使用線程運行套接字和服務器。我的服務器是一個回顯服務器,所以它會發回它收到的任何消息。我的問題是,當我在客戶端和服務器端啓動兩個線程時,它們在到達從輸入流讀取的部分時「凍結」。它可以正常工作到客戶端發送消息的部分。之後,它只是停止,因爲看起來客戶端正在等待消息,即使我已經通過寫入輸出流向服務器發送消息,服務器也是如此。代碼有什麼問題?套接字多線程 - 讀輸入流暫停線程
Client.java
@Override
public void run() {
try {
Socket socket = new Socket("localhost", 22600);
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(
System.in));
System.out.println("Client 1");
while (true) {
System.out.print("\nEnter text : ");
String inputText = input.readLine();
writer.write(inputText);
System.out.println("Client 2");
System.out.println("Client 3");
String s = br.readLine();
System.out.println("CLIENT RECEIVED : " + s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Server.java
@Override
public void run() {
try {
ServerSocket server = new ServerSocket(22600);
Socket socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
System.out.println("Server 1");
while (true) {
System.out.println("Server 2");
String s = br.readLine();
System.out.println("Server 3");
if (s == null) {
System.out.println("NULL SERVER SIDE ERROR");
break;
}
writer.write("ECHO : " + s);
System.out.println("SYSOUT ECHO " + s);
}
server.close();
} catch (Exception e) {
e.printStackTrace();
}
}
它現在。非常感謝!我從來沒有想過這個問題只是由於缺少換行符而造成的。 – JavaFanatic