问题描述
我有典型的情况。我需要通过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.
这篇关于TCP:为什么只有第二次调用Socket.Receive(字节[])返回的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!