Java:防止Socket DataInputStream引发EOFException [英] Java: Prevent Socket DataInputStream from throwing EOFException

查看:331
本文介绍了Java:防止Socket DataInputStream引发EOFException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我遇到的问题是服务器上套接字的DataInputStream在我只希望其阻塞直到接收到下一批数据时一直抛出EOFException。

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.

是否有一种更清洁的方法告诉套接字阻塞,直到有一些数据要读取?我已经尝试过read()和readFully(),但是都没有用。

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.

推荐答案

如果您收到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.

这篇关于Java:防止Socket DataInputStream引发EOFException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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