为什么我的java socket无法自行结束? [英] Why my java socket can't end itself?

查看:194
本文介绍了为什么我的java socket无法自行结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码片段:

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

After my client send the message to the socket, and the programme successfully print the result, but I can't print the 53, until I stop the client socket's connection. What should I do to deal with it? My client is an async socket. Thanks.

推荐答案

当你关闭时,你的while循环结束,当它获得EOF并且从写作方发送EOF时套接字或 - 更优雅 - 关闭输出。
因此,在您的情况下,当发送方调用 socket.shutdownOutput()时,您的while循环将结束。这只关闭输出流并在数据末尾放置一个EOF。

Your while-loop ends, when it gets an EOF and an EOF is sent from the writing side, whenever you either close the socket or - more graceful - shutdown the output. So, in your case, your while-loop will end, when the sending side calls socket.shutdownOutput(). This closes just the output stream and puts an EOF at the end of the data.

我很确定之前已经讨论过这个问题,遗憾的是我再也找不到问题了只是链接。从我的头脑中,写作方应该运行以下代码来优雅地关闭连接:

I'm pretty sure this was discussed before, unfortunately I cannot find the question any more to just link. From the top of my head, the writing side should run the following code to close the connection gracefully:

// 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 socket无法自行结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆