套接字中的问题
当我启动服务器和客户端时,服务器无法接收客户端输入的文字。 我希望服务器显示来自客户端的消息。但服务器似乎挂在“bf.readLine()”上。我不知道为什么... 以下代码...
服务器代码:
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);
}
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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您使用 write() 写入字节,但使用 readln() 读取字节。 Readln 需要在末尾添加“\n”。
You're writing bytes with write(), but reading with readln(). Readln requires a "\n" at the end.