0

How do I, as a tcp server, get the full response from a client?

When I am the client, I simply do:

server_response = b''
buffer = s.recv(BUFFER_SIZE)
while buffer:
    server_response += buffer
    buffer = s.recv(BUFFER_SIZE)

But as I server I can't do that since recv is a blocking call there

The protocol doesn't define the message size, but it's generally either some text with variable lenght, and some times text with variable length and binary data from a file from which the size is included. It defines a marker, which is a \n. When the \n is found the message is over

1 Answers1

0

How do I, as a tcp server, get the full response from a client?

TCP is a stream protocol which has no inherent message boundary. This means there is no such thing as a "full response" unless you now the length up front or have some kind of marker to detect the end of the message or the message ends with the end of the TCP connection.

... The protocol doesn't define the message size.

So no length is known up-front. You need a kind of marker then.

... but it's generally either some text with variable length, and some times text with variable length and binary data from a file from which the size is included

There is no clear distinction between binary and text since binary just means a byte can take any value and thus text is also some kind of binary. You need therefore a clear marker where the text ends (maybe some \0 character or new line). Also size is included for the binary part is not a clear definition of how exactly the size is included. There a different variantes typically used, like as prefix of a fixed size as binary (uint16, uint32...), hex value with new line (like in HTTP chunked encoding), decimal value ...

Once you have a clear and unambiguous definition of how your message looks like you should be able to implement this definition in your message parser. Since your current description does not provide this clearness no further help can be given in the implementation.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • I have a marker, which is a "\n". The message ends there. How do I implement it though? To get the full message up until the "\n" –  Oct 11 '18 at 20:30
  • @Myntekt: see [process socket data that ends with a line break](https://stackoverflow.com/questions/42987650/) or [Reading from a socket until certain character is in buffer](https://stackoverflow.com/questions/9398436/reading-from-a-socket-until-certain-character-is-in-buffer) for how to read until the specific marker. But note that if you have `\n` as marker for the end of the message you cannot really transport binary data as you claim since `\n` might be part of the binary data too. Similar you cannot transport multi-line text data. – Steffen Ullrich Oct 11 '18 at 20:38