- Notifications
You must be signed in to change notification settings - Fork 86
Getting Started (Sockets)
Hüseyin Uslu edited this page Jun 3, 2014
·
1 revision
Here is a simple JsonRpc server example hosted over sockets. You can connect to this server using Putty with a raw connection.
usingAustinHarris.JsonRpc;usingSystem;usingSystem.IO;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;namespaceJsonRpc_socket_example{classProgram{privatestaticobject_svc;staticvoidMain(string[]args){// must new up an instance of the service so it can be registered to handle requests._svc=newexampleService();varrpcResultHandler=newAsyncCallback(
state =>{varasync=((JsonRpcStateAsync)state);varresult=async.Result;varwriter=((StreamWriter)async.AsyncState);writer.WriteLine(result);writer.FlushAsync();});SocketsExample.SocketListener.start(3333,(writer,line)=>{varasync=newJsonRpcStateAsync(rpcResultHandler,writer){JsonRpc=line};JsonRpcProcessor.Process(async,writer);});}}class exampleService : JsonRpcService
{[JsonRpcMethod]// handles JsonRpc like : {'method':'incr','params':[5],'id':1}
private int incr(inti){return i +1;}[JsonRpcMethod]// handles JsonRpc like : {'method':'decr','params':[5],'id':1}privateintdecr(inti){returni-1;}}}namespaceSocketsExample{publicclassSocketListener{publicstaticvoidstart(intlistenPort,Action<StreamWriter,string>handleRequest){varserver=newTcpListener(IPAddress.Parse("127.0.0.1"),listenPort);server.Start();Console.WriteLine(" You can connected with Putty on a (RAW session) to {0} to issue JsonRpc requests.",server.LocalEndpoint);while(true){try{using(varclient=server.AcceptTcpClient())using(varstream=client.GetStream()){Console.WriteLine("Client Connected..");varreader=newStreamReader(stream,Encoding.UTF8);varwriter=newStreamWriter(stream,newUTF8Encoding(false));while(!reader.EndOfStream){varline=reader.ReadLine();handleRequest(writer,line);Console.WriteLine("REQUEST: {0}",line);}}}catch(Exceptione){Console.WriteLine("RPCServer exception "+e);}}}}}
