TCP server: how to avoid message overlapping
I am going to write a TCP server, the client sends me XML message, I am wondering if bel开发者_运维问答ow condition will happen and how to avoid that:
1) client sends <cmd ...></cmd>
2) sever is busy doing something
3) clients sends <cmd ...></cmd>
4) server does a recv() and put the string to buffer
Will the buffer be filled with <cmd ...></cmd><cmd ...></cmd>
or even worse <cmd ...></cmd><cmd ...
if my buffer is not big enough?
What I want is the TCP stack divides the messages to the same pieces as how clients sent them.
Is it doable?
This is impossible to guarantee at the TCP level, since it only knows about streams.
Depending on the XML parser you're using, you should be able to feed it the stream and have it tell you when it has a complete object, leaving the second <cmd...
in its buffer until it is closed also.
You need a higher order protocol to delineate message boundaries as you desire. And there are plenty to choose from including the one that you invent yourself.
You often write clients in the plural form: are there several clients connecting to your server? In this case, each client should be using its own TCP stream, and the issue you are describing should never occur.
If the various commands are send from a single client, then you should write your client code so that it waits for the answer to a command before issuing the next one.
精彩评论