StreamJsonRpc使用TCP数据流通讯
StreamJsonRpc是微软维护的开源JSONRPC的。NET库使用非常方便,常用的操作方式是服务器端通过JsonRpc的Attach静态函数与一个本地类实例实现对外接口,客户端通过Attach方法附加到一个Stream,然后调用Invoke或InvokeAsync函数实现函数的基本操作,详细介绍可参阅https:www。cnblogs。comwillickp13233704。html精致码农相关文章。服务器端
此代码在精致码农示例基础上进行修改,通过示例可以看到使用。NET的Tcp模式建立服务器也是很方便的,因为JsonRpc的Attach函数的形参为Stream对象,只需要在收到客户端连接后获取客户端对象的Stream传入函数即可。usingStreamJsonRpc;usingSystem;usingSystem。IO。Pipes;usingSystem。Net。Sockets;usingSystem。Threading。Tasks;namespaceStreamSample。Server{classProgram{staticasyncTaskMain(string〔〕args){intclientId1;TcpListenerlistenernewTcpListener(System。Net。IPAddress。Any,6600);listener。Start();while(true){Console。WriteLine(等待客户端连接。。。);TcpClientclientawaitlistener。AcceptTcpClientAsync();NetworkStreamstreamclient。GetStream();Console。WriteLine(34;已与客户端{clientId}建立连接);TcpResponseAsync(stream,clientId);clientId;}}staticasyncTaskTcpResponseAsync(NetworkStreamstream,intclientId){varjsonRpcJsonRpc。Attach(stream,newGreeterServer());awaitjsonRpc。Completion;Console。WriteLine(34;客户端{clientId}的已断开连接);jsonRpc。Dispose();awaitstream。DisposeAsync();}staticasyncTaskResponseAsync(NamedPipeServerStreamstream,intclientId){varjsonRpcJsonRpc。Attach(stream,newGreeterServer());awaitjsonRpc。Completion;Console。WriteLine(34;客户端{clientId}的已断开连接);jsonRpc。Dispose();awaitstream。DisposeAsync();}}publicclassGreeterServer{publicstringSayHello(stringname){Console。WriteLine(34;收到【{name}】的问好,并回复了他);return34;您好,{name}!;}}}客户端
与服务器端相似,我们在连接到服务器后获取TcpClient对象的Stream传入Attach函数即可,具体代码如下:usingStreamJsonRpc;usingSystem;usingSystem。IO。Pipes;usingSystem。Net;usingSystem。Net。Sockets;usingSystem。Threading。Tasks;namespaceStreamSample。Client{classProgram{staticstringGetMachineNameFromIPAddress(stringipAddress){stringmachineNamenull;try{IPHostEntryhostEntryDns。GetHostEntry(ipAddress);machineNamehostEntry。HostName;}catch(Exceptionex){System。Console。WriteLine(ex。Message);}returnmachineName;}staticstringGetIPAddressFromMachineName(stringmachineName){stringipAdressstring。Empty;try{IPAddress〔〕ipAddressesDns。GetHostAddresses(machineName);IPAddressipipAddresses〔1〕;ipAdressip。ToString();}catch(Exceptionex){System。Console。WriteLine(ex。Message);}returnipAdress;}staticasyncTaskMain(string〔〕args){TcpClienttcpClientnewTcpClient(192。168。31。67,6600);varstreamtcpClient。GetStream();Console。WriteLine(正在连接服务器。。。);Console。WriteLine(已建立连接!);Console。WriteLine(我是精致码农,开始向服务端问好。。。);varjsonRpcJsonRpc。Attach(stream);varmessageawaitjsonRpc。InvokeAsyncstring(SayHello,精致码农);Console。WriteLine(34;来自服务端的响应:{message});Console。ReadKey();}}}程序运行效果
服务器端
客户端