Java:防止 Socket DataInputStream 抛出 EOFException
我的客户端/服务器应用程序当前每次想要发送/接收数据时都会打开和关闭新连接。我正在尝试更改它,以便它拥有一个持久连接。
我遇到的问题是服务器上套接字的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您收到 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.