Java 通过套接字发送数据 - 为什么需要在字符串末尾添加换行符?
因此,虽然我现在明白为什么在应立即发送数据时需要刷新连接到套接字的输出流,但我仍然不明白为什么需要在字符串末尾添加换行符。
这有效:
// writer is a PrintWriter
writer.println("Hello World!");
这不起作用:
Writer.print("Hello World!");
writer.flush;
So, while I now get why the Outputstream connected to a socket needs to be flushed when data should be sent immediately, I still don't get why I need to put a newline at the end of the String.
This works:
// writer is a PrintWriter
writer.println("Hello World!");
This doesn't:
Writer.print("Hello World!");
writer.flush;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该更准确地定义工作和不工作。客户端和服务器之间的协议是什么?您预计会发生什么以及您观察到什么?
我怀疑服务器只是在执行任何操作之前等待换行符出现在其输入中。如果是这种情况,那么在发送换行符之前刷新客户端的编写器当然不会有帮助。
You should define work and doesn't work more precisely. What's the protocol between the client and the server? What do you expect to happen and what do you observe?
I suspect the server is simply waiting for a newline character to appear in its input before doing anything. If that's the case, then of course flushing the writer at client side before sending the newline won't help.
如果您按照上一个问题使用 BufferedReaders readLine 方法进行读取,则 readLine 将无法完成,除非它找到换行符。
If you are reading with a BufferedReaders readLine method as per your previous question, readLine won't complete unless it finds the newline character(s).