...server and client getting out of sync
Basically you say that your application is buggy. And the way to make the connection more stable is therefor to fix these bugs, not to work around it with some explicit sleep.
While you don't show any code, a common cause of "getting out of sync" is the assumption that a send
on one side is matched exactly by a recv
on the other side. Another common assumption is that send
will actually send all data given and recv(n)
will receive exactly n
bytes of data.
All of these assumptions are wrong. TCP is not a message based protocol but a byte stream. Any message semantics need to be explicitly added on top of this byte stream, for example by prefixing messages with a length or by having a unique message separator or by having a fixed message size. And the result of send
and recv
need to be checked to be sure that all data have been send or all expected data have been received - and if not more send
or recv
would need to be done until all data are processed.
Adding some sleep
often seems to "fix" some of these problems by basically adding "time" as a message separator. But it is not a real fix, i.e. it affects performance but it is also not 100% reliable either.