Search code examples
pythonsocketstcpbuffertcpclient

Recieving TCP socket data by buffer


Do I have to get data from tcp socket with the buffer size? I know the data packages are divided with \n, so is there any way to get data from the server until I hit \n ? python socket package has recv() method accepting buffer as the only parameter.


Solution

  • No; TCP doesn’t provide any message-framing functionality. Recv() will always just give you as many bytes as it can (up to the limit you specified) and then it is up to your code to handle those bytes appropriately regardless of how many (or how few) were passed to you by any given recv() call.

    For example you might add the received bytes to the end of a buffer, then search the buffer for the first newline character; if you find one, remove it and whatever precedes it from the buffer and handle the removed text; repeat until no more new lines are found in the buffer.