问题
How should I design my message protocol so that I distinguish between user data and termination of the message.
For example I take input from user to send it to client over TCP/IP, now the client-side needs to know the length of message, what I thought that I use some kind of termination by which the client recognizes that message end has been reached?
How do I something like this in C++. I'm using Windows sockets
回答1:
A reasonably common strategy for application-specific protocols is, instead of using termination, to encode message length before the message. So the first few bytes (how many varies) specify the message length, and some special code (usually all bits on or all bits off) designates an overlong message that requires continuation.
Edit: An example has been requested. Let's say we've designed our protocol so that the maximum size of a message is 255 bytes, and we want to send the string "hi". Our protocol message will consist of three bytes: 2
, 104
, 105
. The first byte, 2
, tells us the length of the message that follows it. The second and third bytes, 104
and 105
, are ASCII for h
and i
.
回答2:
You could transmit length first, then the message.
回答3:
You can send the message in chunks and prepend each chunk with its length. The stream would be terminated by a chunk of zero length. (This is the way HTTP does it if the stream length isn't known in advance.)
回答4:
There are many computer systems that use special markers to determine the end of a message - c uses \0 on character arrays, JPEG uses 0xFF as a marker, and such.
All these systems lead us to the conclusion that prefixing messages with their length is far more straightforward and robust.
TCP itself actually does this. If you write two bytes of user input to a socket, there will be two bytes available at the other end, and the TCP packets being handled by the system know this because they mark each packet with its payload length.
Once you've done sending input, you can shutdown the socket from one side and the other side will be notified (if they've enabled such notifications).
回答5:
Or, you could follow the example of POP and use a "." at the beginning of an empty line.
来源:https://stackoverflow.com/questions/1333109/messaging-protocol