这是我的代码段:
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
,直到我停止客户端套接字的连接。我该怎么做才能处理它?我的客户端是异步套接字。谢谢。
答案 0 :(得分:1)
你的while循环结束,当它获得EOF并且从写入端发送EOF时,无论何时关闭套接字或 - 更优雅 - 关闭输出。
因此,在您的情况下,当发送方调用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