Reading multiple JSON objects on a JSON-RPC connection

ⅰ亾dé卋堺 提交于 2019-12-11 07:57:42

问题


I am making a streaming API which handles both RPC style calls as well as notifications from the server to the client (not the notifications in the JSON-RPC spec which are client to server). This last part unfortunately rules out JSON-RPC + persistent HTTP.

The API is based on the JSON and JSON-RPC specs.

JSON - http://www.ietf.org/rfc/rfc4627.txt

JSON-RPC - http://www.jsonrpc.org/specification

Typical session might be:

-> Sending to server
<- Receiving from server    

-> {'id': 0, 'method':'login','params':{'token':'secret'}}
<- {'id': 0, 'method':'login','result':0}
-> {'id': 1, 'method':'subscribe','params':{'symbol':'VOD.L'}}
<- {'id': 1, 'method':'subscribe','result':0}
...
<- {'method':'notifyPrice','params':{'symbol':'VOD.L', 'bid':10.1, 'ask':10.03}}
<- {'method':'notifyPrice','params':{'symbol':'VOD.L', 'bid':10.2, 'ask':10.03}}

The above messages, particularly the notifications, could come in any order and in the same packet. Neither of the specs seem to include details of a message separator which makes it difficult to know when an entire JSON message has been received without using a SAX based JSON parser, which are rather rare compared to their DOM counterparts.

Am I missing something obvious, or is there genuinely no standard way to separate between multiple JSON messages coming in over the wire?


回答1:


You are missing something :-)

Each JSON-RPC message is a valid JSON value. A JSON value can by any of:

  • an Array
  • an Object
  • a String
  • a Number

The JSON-RPC envelope is an Object.

If this were a raw socket (like Telnet), then...

Objects start with { and end with }. If you're using the right kind of parser (pull, or event-oriented) at your receiver then it doesn't matter how nested the Objects and Arrays get, you'll still know when you hit that last }.

The above messages, particularly the notifications, could come in any order and in the same packet.

As long as the requests are not interlaved (one finishes before the next starts), then there's no problem at all. It's up to you whether you also require newline termination of the envelope (a.k.a line-oriented protocol).

However, as you're dealing with HTTP...

Why not just use batch messages per the JSON-RPC spec?



来源:https://stackoverflow.com/questions/24471689/reading-multiple-json-objects-on-a-json-rpc-connection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!