Java服务器-TCP套接字检测EOF而不关闭套接字连接

发布于 2024-12-28 07:27:09 字数 344 浏览 3 评论 0原文

当套接字连接保持打开状态时,有没有办法在从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

假面具 2025-01-04 07:27:09

否 - 如果连接保持打开状态,则流尚未到达末尾。流报告 EOF然后稍后获取更多数据的想法违背了流的原则。

如果要通过 TCP 流发送多条消息,最简单的方法是为每条消息添加长度前缀:

HEADER BODY
HEADER BODY
HEADER BODY

然后客户端将读取标头,找出消息的长度,读取它,然后读取下一个标头,等等。

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:

HEADER BODY
HEADER BODY
HEADER BODY

Then the client will read the header, find out how long the message is, read it, then read the next header, etc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文