客户端从 TCP 套接字丢失一些线路
我的 ServerSocket
写出以下几行:
OutputStreamWriter outstream = new OutputStreamWriter(clientSocket.getOutputStream());
BufferedWriter out = new BufferedWriter(outstream);
out.write("Hello");
out.newLine();
out.write("People");
out.flush();
我的客户端像这样读取它:
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while(true){
line = in.readLine();
if(line == null){
ClientDialog.gui.log.append("NULL LINE\r\n");
} else{
ClientDialog.gui.log.append(line+"\r\n");
}
if(in.readLine() == "SHUTDOWN"){
break;
}
}
正如你所看到的,我在套接字上写了“Hello”,一个新行,然后是“People”,但是当我运行我的客户,它只重复打印“Hello”和null。我不明白有什么问题?
问题已解决:
在将“People”写入套接字后,我必须添加一个 out.newLine()
,并且我必须执行 line == "SHUTDOWN “
不是 in.readLine() == "SHUTDOWN"
,因为 in.readLine()
正在消耗“People”。
还建议在 String
类中使用 equals()
方法,而不是 ==
。
谢谢!
这是给未来观众的。
My ServerSocket
writes out the following lines:
OutputStreamWriter outstream = new OutputStreamWriter(clientSocket.getOutputStream());
BufferedWriter out = new BufferedWriter(outstream);
out.write("Hello");
out.newLine();
out.write("People");
out.flush();
And my client reads it like so:
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while(true){
line = in.readLine();
if(line == null){
ClientDialog.gui.log.append("NULL LINE\r\n");
} else{
ClientDialog.gui.log.append(line+"\r\n");
}
if(in.readLine() == "SHUTDOWN"){
break;
}
}
As you can see I write "Hello", a new line, and then "People" on the socket, but when I run my client, it only prints "Hello" and null repeatedly. I don't see what is wrong?
PROBLEM SOLVED:
I had to add an out.newLine()
after I wrote "People" to the socket, and I had to do line == "SHUTDOWN"
not in.readLine() == "SHUTDOWN"
as the in.readLine()
was consuming "People".
It was also recommended to use the equals()
method in the String
class, instead of ==
.
Thanks!
This is for future viewers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每个循环调用 readLine 两次。
上面的代码使用您的“People”行
来修复更改,
此外,您应该在发送“People”后发送换行符
You call readLine twice per loop.
The code above consumes your "People" line
to fix change to
Also you should send a newline after sending "People"
应该是这样
的:
您调用了 readLine() 两次,从而消耗了其中一行
此外,在比较 String 类型时,您应该在字符串类:
This
Should be this:
You are calling
readLine()
twice and thus consuming one of your linesAlso, when comparing String types, you should use the
equals()
method in the String class:我非常确定您的
in.readLine() == "SHUTDOWN"
正在消耗流中的“人”。此外==
也不起作用。I'm pretty sure that your
in.readLine() == "SHUTDOWN"
is consuming the "people" in the stream. Further==
won't work either.发送人员后,您需要发送另一条换行符。您对 readLine 的调用正在等待它发出信号以处理更多数据。
尝试
You need to send another newline after you send people. Your call to readLine is waiting for that to signal it to process more data.
Try