0

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?

Duck
  • 26,924
  • 5
  • 64
  • 92
transilvlad
  • 13,974
  • 13
  • 45
  • 80

2 Answers2

2

You have to know in advance either (1) what the length of message is or (2) what constitutes the end of a message. So either (1) prefix a message with the expected length; or (2) have all messages be the same size; (3) define different message types in which the length is known in advance; or (4) define exactly what constitutes the end (and possibly the beginning) of a message.

In your case possibly two line feeds in a row could signal the EOM. Or a null byte if there are otherwise no null bytes in the strings. Or just have the client send the length first and then the message.

Duck
  • 26,924
  • 5
  • 64
  • 92
1

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.

// NOTE: take care to know if you need to ensure constant MsgHeader size in bytes
// among platforms.
typedef _MsgHeader {
  int m_Type;
  int m_Length;
} MsgHeader;

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!

Community
  • 1
  • 1
Blitzkoder
  • 1,768
  • 3
  • 15
  • 30