Oleg Vazhnev
Oleg Vazhnev

Reputation: 24067

tcp: why only second call to Socket.Receive(byte[]) returns data?

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

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?

Upvotes: 0

Views: 280

Answers (1)

CodesInChaos
CodesInChaos

Reputation: 108790

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.

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

Upvotes: 2

Related Questions