我们如何才能找到从套接字接收到的所有字节?

发布于 2024-10-18 03:55:47 字数 430 浏览 4 评论 0原文

我想知道我们何时从没有 Socket.Disconnect() 的套接字接收所有字节 方法?

然而,我使用此代码来接收所有字节,但当 Scoket.Send(byte[]) 方法完成时,我使用 Socket.Disconnect() 方法。

List<byte> LBytes = new List<byte>();
do
{
System.Threading.Thread.Sleep(50);
BytesRead = obj_socket.Receive(obj_buffer, 0);
LBytes.Append(obj_buffer);
} while (BytesRead != 0);

因为当我们断开套接字时,套接字读取 0 字节。 例如我们发送了 100,000 字节,我们应该接收 100,000 字节。你怎么做到这一点?

I want to know when we receive all bytes from a socket without Socket.Disconnect()
method?

Yet , I use this code to receive all bytes , but i use Socket.Disconnect() method when Scoket.Send(byte[]) method is complete.

List<byte> LBytes = new List<byte>();
do
{
System.Threading.Thread.Sleep(50);
BytesRead = obj_socket.Receive(obj_buffer, 0);
LBytes.Append(obj_buffer);
} while (BytesRead != 0);

because when we disconnect the socket , socket reads 0 bytes .
for example we sent 100,000 bytes , and we should receive 100,000 bytes . How you do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

卖梦商人 2024-10-25 03:55:47

虽然套接字是打开的,但没有办法做到这一点而不导致它在到达末尾时阻塞(期望更多数据)。

有几种方法可以做到这一点:

  • 发送后关闭套接字
  • 有一些表示“消息结束”的标记(使用编码文本很容易 - 0 是常见的选择;发送任意二进制数据时很棘手,不过)
  • 在数据之前发送一个长度前缀(在本例中为 100,000),当你得到这么多时停止读取

如果它是一个 NetworkStream,例如,使用长度前缀:

int expecting = //TODO: read header in your chosen form
int bytesRead;
while(expecting > 0 && (bytesRead = stream.Read(buffer, 0,
        Math.Min(expecting, buffer.Length))) > 0)
{
    // TODO: do something with the newly buffered data
    expecting -= bytesRead;
}

While the socket is open, there is no way of doing this without causing it to block when it reaches the end (expecting more data).

There are several ways of doing it:

  • close the socket after sending
  • have some marker that means "end of message" (easy enough with encoded text - 0 being a common choice; tricky when sending arbitrary binary data, though)
  • send a length prefix before the data (100,000 in this case), and stop reading when you get that much

If it was a NetworkStream, for example, using a length prefix:

int expecting = //TODO: read header in your chosen form
int bytesRead;
while(expecting > 0 && (bytesRead = stream.Read(buffer, 0,
        Math.Min(expecting, buffer.Length))) > 0)
{
    // TODO: do something with the newly buffered data
    expecting -= bytesRead;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文