0

这是我的代码片段:

            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,直到我停止客户端套接字的连接。我应该怎么处理?我的客户端是一个异步套接字。谢谢。

4

1 回答 1

1

你的 while 循环结束,当它得到一个 EOF 并且从写入端发送一个 EOF 时,每当你关闭套接字或者 - 更优雅 - 关闭输出时。因此,在您的情况下,当发送方调用时,您的 while 循环将结束socket.shutdownOutput(). 这仅关闭输出流并在数据末尾放置一个 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
于 2013-08-12T13:43:30.603 回答