连续发送三个或更多数据包时遇到问题

发布于 2024-11-14 21:33:52 字数 559 浏览 3 评论 0原文

我正在尝试使用 TCpClient 实现客户端/服务器模型,其 Networkstream.Write()/Read() 函数发送/接收字节数组。

它在大多数情况下都有效,除非我尝试连续发送三个或更多字节数组。客户端说它发送了全部,但服务器只接收前两个。

下面是我用来从客户端编写到服务器的代码。

byte[] buffer = p.toByteArray(level);

stream.Write(buffer, 0, buffer.Length);
stream.Flush();

是巩固它们还是什么?我只是不明白当我发送 2 个而不是 3 个或更多时,服务器如何接收不同的数组。如果我将 3 个写入分开,它可以正常工作,但我真的不想这样做。

任何帮助将不胜感激。

编辑:

已解决:) 感谢大家的帮助。它一次推送 2-3 个数据包,我的系统认为 1 个突发 = 1 个数据包。我刚刚用 TCPClient 重写了现有的架构来检测多个数据包:) 再次感谢您的帮助!

I am trying to implement a Client/Server model using TCpClient, with its Networkstream.Write()/Read() functions sending/receiving a byte array.

It works most the time, except if I try to send three or more byte arrays in a row right after one another. The client says it sends them all, but the server only receives the first two.

Below is the code I use to write from client to server.

byte[] buffer = p.toByteArray(level);

stream.Write(buffer, 0, buffer.Length);
stream.Flush();

Is it consolidating them or something? I just don't understand how the server can receive distinct arrays when I send 2, but not 3 or more. If I separate the 3 writes, it works OK, but I really don't want to do that.

Any help would be much appreciated.

EDIT:

SOLVED :)
Thanks for all your guys help. It was pushing 2-3 packets at a time, and my system was thinking 1 burst = 1 packet. I just rewrote my existing architecture with TCPClient to detect multiple packets :) Again, thanks for the help!

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

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

发布评论

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

评论(1

孤千羽 2024-11-21 21:33:52

当您进行套接字编程时,有一个非常重要的核心规则需要考虑:

不能保证无论客户端在 X 中发送什么写入,服务器都会收到完全相同的读取量。客户端可以写入 1 次,服务器可以读取 10 次。客户端可以进行 10 次写入,而服务器上只能进行 1 次读取。

假设客户端发送 3 条消息,每条 100 字节。服务器可能会接收 150 个字节,然后再接收另外 150 个字节。或者100字节和200字节。

如果您使用 TCP,唯一可以保证的是顺序将被保留,换句话说,您首先发送的任何内容都将首先到达服务器。

您可以使用以下基本技术之一来分隔数据:

  • 标记(分隔消息的某种字节序列)
  • 每个消息长度的恒定长度
  • 消息头组合中
  • 上述

There is one very important core rule that is important to account for when you do Sockets programming:

It is not guaranteed that whatever client sent in X writes, server will receive exactly in the same amount of reads. It can be one write on client and 10 reads on server. It can be 10 writes and client and just one read on server.

Let's say the client sends 3 messages, 100 bytes each. Server might receive 150 bytes and then another 150 bytes. Or 100 bytes and 200 bytes.

The only thing that is guaranteed if you work with TCP is that the order will be preserved, in other words that whatever you sent first will arrive first on the server.

You can use one of the following basic techniques to separate the data:

  • markers (some kind of byte sequence that delimit messages)
  • constant length per message
  • length in the message header
  • combination of the above
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文