Java:防止 Socket DataInputStream 抛出 EOFException

发布于 2024-10-12 19:44:32 字数 464 浏览 2 评论 0原文

我的客户端/服务器应用程序当前每次想要发送/接收数据时都会打开和关闭新连接。我正在尝试更改它,以便它拥有一个持久连接。

我遇到的问题是服务器上套接字的 DataInputStream 不断抛出 EOFException,当我只想阻止它直到收到下一批数据时。

我想过只是简单地像这样编写服务器......

while socket is open {
    while at socket's DataInputStream's EOF {
        wait a second
    }
    //If we're here, then we have some data
    do stuff
}

但这非常难看,并且不是在收到某些数据之前阻塞的正确方法。

有没有更干净的方法来告诉套接字阻塞,直到有一些数据要读取?我尝试过 read() 和 readFully(),但都不起作用。

My client/server application currently keeps opening and closing new connections every time it wants to send/receive data. I'm trying to change it so it will have one persistent connection.

The problem I'm having is the socket's DataInputStream on the server keeps throwing EOFException's when I just want it to block until it receives the next batch of data.

I thought about just simply writing the server like this...

while socket is open {
    while at socket's DataInputStream's EOF {
        wait a second
    }
    //If we're here, then we have some data
    do stuff
}

... but this is extremely ugly and not the proper way to block until some data is received.

Is there a cleaner way to tell the socket to block until there's some data to read? I've tried read() and readFully(), but neither work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

亽野灬性zι浪 2024-10-19 19:44:32

如果您收到 EOFException,则意味着连接已断开。您无法等待已关闭的连接。继续处理您的客户端代码,以免它关闭连接。在服务器端,任何读取方法都将阻塞,直到数据可用为止,而无需您进一步努力。

If you are getting EOFException, it means the connection is gone. You cannot wait on a connection that's closed. Keep working on your client code so that it doesn't close the connection. On the server side, any of the read methods will block until data is available without further effort from you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文