简体   繁体   中英

C++ socket reading side reads all messages concatenated

Hi I have a socket programming with C# Socket Server and C++ Socket Client.

Server I use Socket.Send(bytes[]) to send message

CPP Client side i use recv(socket,buffer,length,flags) But in server if i send multiple messages concurrently on the client side i recieve all messages as concatenated.

for(int i=0;i<10;i++)
{
var bytes= GetBytes("msg"+i);
theSocket.Send(bytes);
}

C++ Socket CLient:

Thread.Start()
{
   var msg = recv(theSocketClient,buffer,1024,0);
   ProcessMessageFromSocket(msg);
}

Expected is: process msg1 then Process msg2... Process msg10 Actual: processMessage(msg1msg2msg3...msg10 );

What i am missing? my attempts to fix this: 1. C# NetworkStream.Flush() -- Even after this it gives me concatenated strings 2. CPP Everytime after finishing the read i erase the buffer (but the actual socket has data concatenated so this did not help)

It's normal for it to work this way. It's up to you to define your own protocol for splitting up data, for example you might to choose to start each transmission with 4 bytes telling you how long that transmission is.

Simples - TCP cannot transfer any messages longer than one byte - it's an octet/byte stream.

If you want to transfer messages longer than one byte, you need another protocol on top of TCP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM