Java: Prevent Socket DataInputStream from throwing EOFException

﹥>﹥吖頭↗ 提交于 2019-12-23 02:04:22

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/4729277/java-prevent-socket-datainputstream-from-throwing-eofexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!