0
當我啓動服務器和客戶端時,服務器無法接收到在客戶端鍵入的單詞。 我希望服務器顯示來自客戶端的消息。但服務器似乎掛在「bf.readLine()」上。我不知道爲什麼...以下代碼 ...插座故障
Server代碼:
ServerSocket ss = new ServerSocket(11111);
System.out.println("current port:"+ss.getLocalPort());
Socket s = ss.accept();
System.out.println("remote port:"+s.getPort());
BufferedReader bf = new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true)
{
String str = bf.readLine();
System.out.print(s.getPort()+": ");
System.out.println(str);
if ("bye".equals(str))
break;
}
,然後客戶端代碼:
Socket s = new Socket("127.0.0.1",11111);
System.out.println("connected to remote server:"+s.getPort());
System.out.println("My port:"+s.getLocalPort());
PrintWriter pw = new PrintWriter(s.getOutputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
Scanner in = new Scanner(System.in);
while (true)
{
System.out.print("I said: ");
String l = in.next();
pw.write(l);
pw.flush();
System.out.println("Echo~~~~"+l);
}
嘗試使用[PrintWriter](http://download.oracle.com/javase/1.4.2/docs/api/java/io/PrintWriter.html).println(l)。 – Sajid 2011-04-11 05:34:33
我假設你的意思是'readLine()' – 2011-04-11 05:35:31
@PgygyZhu,簡而言之,將'pw.write(l);'改爲'pw.println(l);' – 2011-04-11 05:37:29