c++socketscasyncsocket

C++ Stop CAsyncSocket splitting single large packet to multiple small packets


I'm writing a client that connects to a server

Sometimes the server send dome special packets to the client with the size of 30kb but on client side I get that 30kb in multiple smaller packets (1kb) so my OnReceive callback calls almost 30 times until I get the full packet.

I managed to solve this problem by putting an Sleep(1000) just right before CAsyncSocket::Receive and then I get all 30kb in one single packet but putting Sleep() is a very bad idea.

Is there any configuration that I should do for CAsyncSocket ?


Solution

  • No. There is no way to do this because that's not how TCP sockets work. TCP does not deliver packets, it delivers streams of data. It may be that your packet will be delivered in one piece because it's convenient to do so or it may split the packets or combine them with other packets.

    The only reliable way to do this is for the receiving end to know how many bytes it needs and keep reading until it's got that many. That may mean sending a packet length in front of each packet for example.