Java服务器-TCP套接字检测EOF而不关闭套接字连接
当套接字连接保持打开状态时,有没有办法在从 TCP 套接字读取数据时检测 EOF?
我见过的大多数示例都是这样的:
int n=0;
While((n = read.inStream(data)) != -1){
destType.write(data, 0, n);
}
然而,这意味着每次您想要接收新数据时都被迫创建一个新连接。 就我而言,这是通过套接字作为字节发送的恒定图像流,我想处理每个图像而不必关闭之间的连接,以便我可以拥有与单个用户关联的所有图像以及它只是不频繁地频繁打开和关闭连接会更有效。
那么有没有办法做到这一点或提供一些有关可能替代方案的信息?
Is there a way to detect the EOF when reading from a TCP Socket whilst the socket connection stays open?
Most of the examples I have seen are something along the lines of:
int n=0;
While((n = read.inStream(data)) != -1){
destType.write(data, 0, n);
}
However this means that you are forced to create a new connection every time you want to receive a new piece of data.
In my case this is a constant stream of images that are sent across the socket as bytes and I would like to process each image without having to close the connection between so that I can have all the images associated with a single user, aswell as it is just more efficient to not constantly open and close connections at a high frequency.
So is there a way to do this or some information on a possible alternative?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
否 - 如果连接保持打开状态,则流尚未到达末尾。流报告 EOF然后稍后获取更多数据的想法违背了流的原则。
如果要通过 TCP 流发送多条消息,最简单的方法是为每条消息添加长度前缀:
然后客户端将读取标头,找出消息的长度,读取它,然后读取下一个标头,等等。
No - if the connection stays open, the stream hasn't reached its end. The idea of a stream reporting EOF and then having more data later goes against the principle of a stream.
If you want to send multiple messages across a TCP stream, the simplest way is to prefix each message with its length:
Then the client will read the header, find out how long the message is, read it, then read the next header, etc.