TCP:为什么只有第二次调用Socket.Receive(字节[])返回的数据?字节、数据、TCP、Socket

2023-09-03 08:00:21 作者:能动手尽量少BB

我有典型的情况。我需要通过TCP发送请求到服务器并接收响应。

I have typical situation. I need to send "request" to server via tcp and receive response.

// socket is connected
socket.Send(CreateRequest());
byte[] br = new byte[VERY_BIG_BUFFER];
int count = socket.Receive(br);   // only 4 bytes received: 15 0 0 0
count = socket.Receive(br);       // here I receive data I actually need

但由于某种原因我必须调用 socket.Receive 两次,以使一切工作。 在额外调用我刚刚收到四个字节:15 0 0 0

However by some reason I have to call socket.Receive twice to make everything works. In extra call I receive just four bytes: 15 0 0 0.

硬编码一个额外的电话。难道有人知道发生了什么事情,为什么我需要额外的电话吗?

Hardcoding one extra call without understanding why I need it may result in odd problems. Do someone know what's going on and why I need extra call?

推荐答案

TCP是基于流的协议。它不具有消息的概念。这是字节只是一个序列。

TCP is a stream based protocol. It doesn't have a concept of messages. It's just a sequence of bytes.

这意味着它可以被分割成一个发送调入多个收到通话,并且可以将多个发送调用到一个收到电话,或它们的组合。

This means that it can split one send call into multiple receive calls, and can combine multiple send calls into one receive call, or a combination thereof.

您需要以某种方式分隔您的邮件。一定长度的preFIX是二进制协议的热门之选。

You need to delimit your messages somehow. A length prefix is a popular choice for binary protocols.

 
精彩推荐
图片推荐