I have a simple socket server that is supposed to receive a string and return another.
The string received is multi-line.
Is there a way to tell when the client finished sending without having a predefined end of transmission set of characters added at the end?
I have a simple socket server that is supposed to receive a string and
Share
Adding to what was said, you could perhaps define a small fixed-size structure to use as a protocol message header. And as wildplasser added, you should be careful with endianness and sizes.
If you are working with the Berkeley sockets API, you should look into htons() and htonl() to account for possibly different network byte ordering. Regarding integer sizes across different platforms, this thread may be of interest.
Whenever a participant of the communication wishes to send a string, that participant must first send a message with sizeof(MsgHeader) and the receiver (server in this case), expecting a message, just reads sizeof(MsgHeader) bytes, casts the result to MsgHeader and proceeds to read the m_Length field to find out what byte count to expect from the string that will then be sent.
You could then also use the m_Type field to differentiate message contexts, but if not needed for now, just sending the length at the beginning of each message is fine.
You mentioned that the received string is multi-line, so I assume you mean they’re all separated by newline characters. If that’s so, you could just concatenate the sender’s strings into one larger string, get its length and send it all as one piece, assuming there isn’t some problem-specific aspect that prevents this. Just a heads-up, it might be useful to set the receiving buffer to zero, so when you receive the string, it will already have a terminating character ‘\0’ at the end, in case you’re not sending that in the message.
Hope that was of some help!