我们怎样才能找到所有字节从插座接收? [英] How can we find that all bytes receive from sockets?

查看:115
本文介绍了我们怎样才能找到所有字节从插座接收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道,当我们收到的所有字节从插座没有Socket.Disconnect()
法?

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

不过,我用这个代码,即可获得所有字节,但我用Socket.Disconnect()方法时Scoket.Send(字节[])方法就完成了。

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);



因为当我们拔掉插座,插座读取0字节。
为例,我们派出100,000字节,我们应该接受100,000字节。你是怎么做到这一点?

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?

推荐答案

而插座的打开的,有没有这样做的方式。不会使它当它达到(期待更多的数据)结束块

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).

有这样做的几种方法:


  • 发送

  • 后关闭套接字有一些标记,这意味着消息的结束(很容易的具有编码文本 - 0 是共同的选择;发送时任意的二进制数据,虽然)

  • 棘手发送在这种情况下的数据之前,一个长度前缀(100,000),和<青霉>停止阅读的,当你得到这么多

  • 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

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

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;
}

这篇关于我们怎样才能找到所有字节从插座接收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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