How to handle corrupt messages arriving on a socket?

Posted by Pieter on Stack Overflow See other posts from Stack Overflow or by Pieter
Published on 2010-04-19T09:48:25Z Indexed on 2010/04/19 9:53 UTC
Read the original article Hit count: 714

I've got a working socket handling mechanism, similar (but a bit more complex) to Qt's Fortune Example
http://qt.nokia.com/doc/4.5/network-fortuneclient.html
http://qt.nokia.com/doc/4.5/network-fortuneserver.html

Now I'm wondering how to handle corrupt messages. Discarding the data is a start, but I need to discard up to a point I can start processing messages again. The corrupt message may be lost, but I need to be able to recover from it. I've got the following idea in mind:

Put a fixed header at the start of each message, eg. 0xABCDEF01. When recovering, lookup this header and restart handling incoming messages.
=> Break off readFortune() on a timeout and recover
=> When encountering an inconsistent header, recover

A huge blocksize is still going to be a problem. To fix that, I should be constantly checking whether or not I'm reading gibberish, but this is not always possible. I can also limit the blocksize on certain message-types.

Any ideas on this? Any proposals on what to use as byteword?

© Stack Overflow or respective owner

Related posts about socket-programming

Related posts about text-parsing