C# void ReceiveData(IAsyncResult iar)

发布于 2024-08-16 15:19:04 字数 627 浏览 5 评论 0原文

我需要以下方面的帮助。这与异步套接字有关。

from the sender:

string stringData = "Welcome to my server server server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);

//MessageBox.Show(message1.Length.ToString());

client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);

这里可以看出,可以找到message.length。

--

在客户端上:

  Socket remote = (Socket)iar.AsyncState;
  int recv = remote.EndReceive(iar);
  string stringData = Encoding.ASCII.GetString(data, 0, recv);

我的问题是有没有办法访问发送数据的实际长度,并根据该调用接收数据,直到收到完整的消息?

i would like some help with the following. this is to do with Asynchronous sockets.

from the sender:

string stringData = "Welcome to my server server server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);

//MessageBox.Show(message1.Length.ToString());

client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client);

here as can be seen, the message.length can be found.

--

on the client:

  Socket remote = (Socket)iar.AsyncState;
  int recv = remote.EndReceive(iar);
  string stringData = Encoding.ASCII.GetString(data, 0, recv);

my question is is there a way to access the actual length of the sent data and based on that call recieve data until the complete message is recieved?

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

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

发布评论

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

评论(2

回忆追雨的时光 2024-08-23 15:19:04

否 - TCP/IP 是一种协议。仅仅因为您通过一次调用发送了数据,并不意味着它将作为一个数据包发送,或者它不会与其他数据包合并。换句话说,发送“X”然后“Y”相当于发送“XY”——它们很可能使用完全相同的数据包进行传输,而另一端无法区分。

如果您想要流中的单个“消息”的想法,您应该在数据前面加上几个字节,明确说明其长度。 (另一种方法是使用分隔符,但我更喜欢使用长度前缀 - 它可以更轻松地知道您还需要接收多少数据,您无需担心开始使用下一条消息,并且您不必担心以某种形式转义分隔符。)

No - TCP/IP is a stream protocol. Just because you've sent the data with one call doesn't mean it will be sent as one packet, or that it won't be merged with other packets. In other words, sending "X" then "Y" is equivalent to sending "XY" - they may well be transmitted with the exact same packets, indistinguishable to the other end.

If you want the idea of an individual "message" in a stream, you should prefix the data with a few bytes explicitly stating its length. (An alternative is to use a delimiter, but I far prefer using a length prefix - it makes it easier to know how much data you've still got to receive, you don't need to worry about starting to consume the next message, and you don't have to worry about escaping the delimiter in some form.)

不再见 2024-08-23 15:19:04

仅当传输某些内容以传达长度时 - 将长度预先添加到消息中,或发送某种类型的终止符。

Only if something is transmitted to communicate the length - either pre-pend the length to the message, or send a terminator character of some kind.

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