سؤال

I'm working on implementing a JSON RPC connection over TCP/IP and I have one fundamental issue. Currently I'm using a synchronous approach, which works well.

I can send

{"id":1,"jsonrpc":"2.0","method":"Input.Home"}

and receive

{"id":1,"jsonrpc":"2.0","result":true}

This works with no problems. The issue arises when I receive notifications. These can arrive unpredictably and at any time. I am interacting with the XBMC JSON RPC API. If a notification has been sent by XBMC, I receive multiple JSON requests at once. E.g.

{"jsonrpc":"2.0","method":"GUI.OnScreensaverActivated","params":{"data":null,"sender":"xbmc"}}{"jsonrpc":"2.0","method":"GUI.OnScreensaverDeactivated","params":{"data":null,"sender":"xbmc"}}

This causes a crash in JSON.NET, and understandably so. My first instinct is I need to asynchronously receive these notifications so that I don't have to wait until the next method is called to receive them. However this complicates the simple example I showed above because I can no longer utilize the synchronous calls. i.e.

SendJson(json);
result = ReceiveJson();

Is there a clean way to implement this without over complicating it? Any/All advice is appreciated.

هل كانت مفيدة؟

المحلول

Here is where all the reading is. Its all worth it if you want to get into it. http://msdn.microsoft.com/en-us/library/ms228969.aspx

For a summary though..

Basically what needs to happen is you need to create an object that implements IAsyncResult. This will store state about your async operation, and a callback for when it is complete.

Create a method that can take your IAsyncResult object as input, and before the method returns, it should call .SetCompleted() on your IAsyncResult object. Its inside this method that you do the work you normally do.

Then you will create an instance of your IAsyncResult object (set its data, and callback), then call Task.Factory.StartNew([YourNewMethod],[YourInstanceOf IAsyncResult]).

That is the core of what needs to happen. Just make sure to set your callback and handle exceptions.

If you want a working example of how I and using an async http handler to do json-rpc, take a look at http://jsonrpc2.codeplex.com/SourceControl/changeset/view/13061#74311 also where Process is being called and the async object is being setup http://jsonrpc2.codeplex.com/SourceControl/changeset/view/13061#61720

Hope that helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top