开发者

Java: Prevent Socket DataInputStream from throwing EOFException

开发者 https://www.devze.com 2023-02-05 22:50 出处:网络
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.

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号