H_squared
H_squared

Reputation: 1271

detect a certain string (command) in TCP stream

I'm developing a protocol on top of TCP. I'm wondering what is the best way to detect control messages in this case. Example:

Client sends the control message START. Server sends data ABCD, then sends the control message END. Client detects END and closes connection

The issue is that "END" can be fragmented. So the client might end up reading ABCDEN and then D. What would be the optimal way to detect the control message "END" in this case?

Note: The server does not know how many bytes in total it will be sending!

Upvotes: 1

Views: 106

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596713

TCP is a byte stream, it has no concept of message boundaries, so you must delimit your messages in your protocol. The receiver of a message can then look for the delimiter to know where one message ends and the next begins. For a text-based protocol like you showed, CRLF (a carriage return followed by a line feed) is a commonly used delimiter in many text-based Internet protocols, including HTTP, FTP, POP3, SMTP, etc. In the case of variable-length data, you still need an end-of-data delimiter if you can't send the data size ahead of time. In your example, sending "\r\nEND\r\n" after the data would act as that delimiter.

Upvotes: 3

Related Questions