Hi,
> But what then? Since TCP is a streaming protocol, how would
> the server resync back with the client and start processing requests again?
you *always* need some way to tell the server that the request/transmittion
is complete and some error handling/error recovery. I know several ways:
1. One connection per transmission:
Use a separate connection for each request/response-pair, and shutdown
the writing side of the socket after the data is sent. Use a timeout
to remove old connections with broken/truncated/stalled transmissions.
This is quite simple and straigt forward, and works well.
My own JSON-RPC library works this way.
2. Send several requests/responses over a single TCP connection:
If you really need to send several requests over a single TCP
connection (e.g. if you *really* need the performance), you could
use a TCP connection for several JSON-RPC transmissions. But then,
things get a bit more complicated:
a) detect the end of a JSON-RPC transmission
You have to detect when a JSON-object is complete, by e.g.:
- using a streaming JSON-decoder, which detects when a JSON-object
is complete; unfortunately, most JSON-decoders cannot do this.
- using a "JSON-splitter", which detects the end of a JSON-object
(I wrote one in Python in about 50 LOC)
- using some small self-delimiting encoding on top of TCP; I would
prefer Netstrings (
http://en.wikipedia.org/wiki/Netstring).
b) error-recovery
You have to detect incomplete/broken/truncated JSON-objects, and
re-sync to the next valid JSON-object.
In my opinion, this should be done by timeout and re-connect:
If a JSON-RPC-transfer does not complete in a specific time, send
back all outstanding responses + a parse error, then close the
connection and wait for the client to reconnect.
I would recommend to use one connection per transmission (1).
If you think that this costs too much performance for your application,
then please read about the advantages and disadvantages of persistent
connections (e.g.
http://en.wikipedia.org/wiki/HTTP_persistent_connection),
before chosing (2).
> Similarly, how would it handle a truncated message?
>
> --> {"jsonrpc": "2.0", "method": "foo", "params": [1, 2,
Respond with a parse error (after a timeout) and close the connection.
regards,
Roland