![](/img/trans.png)
[英]Java socket server cannot receive many data at the same time, how to make java socket server accept data at the same time?
[英]Server accept socket but after that the socket cannot receive anything
在構建客戶端 - 服務器聊天程序時,我遇到了一個非常奇怪的問題(因為這總是起作用)。
serversocket接受客戶端的傳入連接沒有任何問題,但是當我嘗試從套接字的輸入流中讀取時,整個方法阻塞並且僅在我關閉客戶端套接字時釋放。
我甚至嘗試使用docs.oracle.com上的示例代碼,但問題仍然存在。
任何人都可以指出我顯然沒有看到的錯誤嗎?
服務器代碼:
public class Server {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
System.out.println("Creating server socket");
ServerSocket internetSocket = new ServerSocket(60000);
if(!internetSocket.isClosed()) {
while(true) {
Socket s = internetSocket.accept();
System.out.println("accepted socket!");
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
}
客戶代碼:
public class Client {
public static void main(String[] args) throws IOException {
Socket s = null;
try {
s = new Socket("localhost", 60000);
} catch (UnknownHostException ex) {
Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter outStream = new PrintWriter(s.getOutputStream());
for(int i=0; i<10; i++) {
outStream.println("test");
System.out.println("Sending the message \"test\"");
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(Start2.class.getName()).log(Level.SEVERE, null, ex);
}
}
s.close();
}
}
方法readLine()
正在等待\\ n字符出現在流中(方法阻塞,直到它看到結束行分隔符)。
嘗試從客戶端發送"test\\\\n"
,看看會發生什么。
並記住在客戶端flush()
輸出流
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.