[英]BufferedReader in Socket Programming
当我尝试从客户端发送输入时,如果我不在字符串末尾连接“\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();
}
}
}
如果您只想读取已发送的部分数据,请使用read(char[])
方法而不是readLine
方法。 此方法以int
形式返回读取的字符数。 例子:
char[] buffer = new char[2000];
int read;
if ((read = in.read(buffer)) != -1) {
String line = new String(buffer, 0, read);
System.out.println("Received from client: " + line);
out.write("Echoing: " + line);
out.flush();
}
接下来您会看到此代码有时无法读取您从 PHP 发送的整个消息,或者将两条或多条消息作为一条读取。
如果你想解决这个问题:
这永远不会奏效,也不是因为 PHP 或 Java。 您正在使用 TCP,一个面向 stream 的协议。 无法保证您从 PHP 程序写入到套接字的消息将一体地到达接收器。 该消息可能被分解,您需要多个套接字 function 调用来读取它。 或者它可能 go 另一个方向,并且单个调用read
返回多个消息。
解决方案是为消息添加某种框架,以便接收者知道何时收到完整的消息。 如果消息本身是单行,则始终以换行符结束消息作为框架。 另一种解决方案是放弃 TCP 并改用面向消息的协议(如 UDP),但这会带来其自身的复杂性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.