Java:防止Socket抛出EOFException [英] Java: Prevent Socket from throwing EOFException

查看:190
本文介绍了Java:防止Socket抛出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抛出EOFException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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