Reputation: 15
When I started the server and client, the server can't receive the words typed in client. I hope the server show the messages from the client. But the server seemed hanging on the "bf.readLine()". I don't know why... following the codes...
Server code:
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;
}
and then the client code:
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);
}
Upvotes: 0
Views: 300
Reputation: 4421
You're writing bytes with write(), but reading with readln(). Readln requires a "\n" at the end.
Upvotes: 4