我正在尝试修复 java 套接字通信错误,其中服务器不知道输入消息长度。在当前情况下,服务器测试输入是否使用 inputStream.available();
方法完成。然而,这种方法并不总是返回正确的答案。它会导致读取部分输入。似乎有两种不同的可能性来解决这个问题。
客户端应发送输入大小。
客户端应在发送后关闭其输出流,但这会导致客户端无法读取响应,因为关闭输出流时套接字也随之关闭。
还有其他建议吗,特别是在 nio 软件包的帮助下?
谢谢。
最佳答案
您可以使用
socket.shutdownOutput();
关闭客户端的输出流。这将显示为关闭的输入流,而不关闭套接字。
顺便说一句:你不能像我一样使用 socket.getOuputStream().close();
。
恕我直言,发送长度是最好的选择,因为这将允许您使用同一套接字发送多个请求。
<小时/>这是一个例子
public class SimpleServerMain {
public static void main(String... args) throws IOException, InterruptedException {
ServerSocket ss = new ServerSocket(54321);
Socket s = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
for (String line; (line = br.readLine()) != null; )
System.out.println("Got " + line);
PrintStream ps = new PrintStream(s.getOutputStream());
for (String word : "Hello World Bye Bye!".split(" ")) {
ps.println(word);
Thread.sleep(1000);
}
s.close();
ss.close();
}
}
和
public class SimpleClientMain {
public static void main(String... args) throws IOException {
Socket s = new Socket("localhost", 54321);
InputStream inputStream = s.getInputStream();
s.getOutputStream().write("Hello\n".getBytes());
s.shutdownOutput();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
for (String line; (line = br.readLine()) != null; )
System.out.println("Got " + line);
System.out.println("Disconnected.");
s.close();
}
}
关于java - 未知输入长度的套接字通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16854988/