【发布时间】:2020-11-02 13:36:35
【问题描述】:
当我尝试从客户端发送输入时,如果我不在字符串末尾连接“\r\n”,我的输入流将永远等待。我看过各种类似的帖子,但找不到合适的解决方案。我的代码如下:
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String line;
if (in.ready()) {
if ((line = in.readLine()) != null) {
System.out.println("Received from client: " + line);
out.write("Echoing: " + line);
out.flush();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
try {
in.close();
clientSocket.close();
System.out.println("Closing connection from " + socketAddress + ", #" + connectionId);
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】:
-
一个因素当然是
readLine()返回没有尾随换行符的行(\r\n、\n、NEL 字符)。out.write("\r\n");还不错。 -
我无法在客户端修改代码。我需要在服务器端采用不同的方法。
-
客户端如何告诉服务器它已经发送了一个完整的消息?你能发布客户端的代码或它使用的通信协议的文档吗?
-
客户端代码是PHP,我写了一个简单的脚本来测试。将与服务器通信的真实设备只能发送原始字节。
socket_write($socket, $message, strlen($message)) -
服务器如何知道它是否收到了完整的
$message,或者它是否必须等待来自客户端的更多数据?另外,当您在 cmets 中回复某人时,请使用 @ 标记用户,否则他们不会收到通知
标签: java sockets inputstream bufferedreader