Aquarius_Girl
Aquarius_Girl

Reputation: 22916

How to tell the TCP server that the particular message has ended?

TCP client sends data byte by byte. So, how to tell the server that this message has ended and the new message begins now?

One way is to fix a special character that'll be sent as a bookmark, but that character can also be a part of the message causing confusions.

Any other optimum way out?

Upvotes: 3

Views: 520

Answers (4)

MarcF
MarcF

Reputation: 3299

Checkout the implementation used in networkComms.net, the open source communication framework. In particular IncomingPacketHandleHandOff() on line 892 here.

It guarantees that the first byte received specifies the size of a packet header (Less than 255 bytes). Once enough bytes have been received in order to rebuild the header, the header can be inspected to determine remaining size to be received (data section). If you have more incoming bytes than the expected header and data sections you look at the very first byte and start over.

Using bookmarked characters is what is used at the base level of the network stack but must be implemented carefully to avoid further complications.

Upvotes: 2

Jestan Nirojan
Jestan Nirojan

Reputation: 2486

If the message is binary, delimited encoding using a special character is not possible. Tag Length Value (TLV) encoding will be best suited for this.

for example

 +--------+----------+----------------+    
 |  Tag   | Length   |  Content       |    
 | 0x0001 |  0x000C  | "HELLO, WORLD" |    
 +--------+----------+----------------+

in addition to that, you can have more than one message type

Upvotes: 2

Ed Heal
Ed Heal

Reputation: 60007

If you wish to use a character as both the end of message marker or as a part of the message, you need to use an escape sequence.

For example: Use the character '$' to end the message, and '%' to escape

i.e.

%$ -> $
%% -> %

then use '$' to end the message

All alternatively send the number of bytes to be received at the start of the messssage (or message chunk if you do not know the lenght of the complete message at that point).

Upvotes: 1

MARK
MARK

Reputation: 2362

One possible way can be that before sending the actual message you can send the number of bytes in the particular message. When the receiving side has received that number of bytes it can start receiving next message

Upvotes: 2

Related Questions