这是我的代码片段:
BufferedInputStream in = new BufferedInputStream(
server.getInputStream());
LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(
in);
byte[] contents = new byte[1024];
System.out.println("45");
int bytesRead = 0;
String s;
while ((bytesRead = ledis.read(contents)) > 0) {
System.out.println(bytesRead);
s = new String(contents, 0, bytesRead);
System.out.print(s);
}
System.out.println("53");
当我的客户端将消息发送到套接字后,程序成功打印结果,但我无法打印 53
,直到我停止客户端套接字的连接。我该怎么办?我的客户端是一个异步套接字。谢谢。
最佳答案
当你的 while 循环得到一个 EOF 并且从写入端发送一个 EOF 时,每当你关闭套接字或者 - 更优雅的 - 关闭输出时,你的 while 循环就结束了。
因此,在您的情况下,当发送方调用 socket.shutdownOutput()
时,您的 while 循环将结束。这仅关闭输出流并在数据末尾放置一个 EOF。
我很确定之前已经讨论过这个问题,不幸的是我找不到更多的问题来链接。从我的想法来看,编写方应该运行以下代码来优雅地关闭连接:
// lets say the output stream is buffered, is namend bos and was created like this:
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
// Then the closing sequence should be
bos.flush();
socket.shutdownOutput(); // This will send the EOF to the reading side
// And on the reading side at the end of your code you can close the socket after getting the EOF
....
while ((bytesRead = ledis.read(contents)) > 0) {
System.out.println(bytesRead);
s = new String(contents, 0, bytesRead);
System.out.print(s);
}
System.out.println("53");
server.close; // <- After EOF was received, so no Exception will be thrown
关于java - 为什么我的java套接字无法自行结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18187022/