StreamJsonRpc使用TCP数据流通讯

StreamJsonRpc是微软维护的开源JSON-RPC.NET库使用非常方便,常用的操作方式是服务器端通过JsonRpcAttach静态函数与一个本地类实例实现对外接口,客户端通过Attach方法附加到一个Stream,然后调用InvokeInvokeAsync函数实现函数的基本操作,详细介绍可参阅https://www.cnblogs.com/willick/p/13233704.html精致码农相关文章。
我在搜索StreamJsonRpc相关资料时发现网上全是使用Pip管道实现的进程间通讯,本文介绍如何使用TCP实现不同主机的网络通讯。

服务器端

此代码在精致码农示例基础上进行修改,通过示例可以看到使用.NETTcp模式建立服务器也是很方便的,因为JsonRpcAttach函数的形参为Stream对象,只需要在收到客户端连接后获取客户端对象的Stream传入函数即可。

using StreamJsonRpc;
using System;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace StreamSample.Server
{
    class Program
    {
        static async Task Main(string[] args)
        {
            int clientId = 1;

            TcpListener listener = new TcpListener(System.Net.IPAddress.Any, 6600);
            listener.Start();

            while (true)
            {
                Console.WriteLine("等待客户端连接...");
                TcpClient client = await listener.AcceptTcpClientAsync();
                NetworkStream stream = client.GetStream();
                Console.WriteLine($"已与客户端 #{clientId} 建立连接");

                _ = TcpResponseAsync(stream, clientId);

                clientId++;
            }
        }

        static async Task TcpResponseAsync(NetworkStream stream, int clientId)
        {
            var jsonRpc = JsonRpc.Attach(stream, new GreeterServer());
            await jsonRpc.Completion;
            Console.WriteLine($"客户端 #{clientId} 的已断开连接");
            jsonRpc.Dispose();
            await stream.DisposeAsync();
        }

        static async Task ResponseAsync(NamedPipeServerStream stream, int clientId)
        {
            var jsonRpc = JsonRpc.Attach(stream, new GreeterServer());
            await jsonRpc.Completion;
            Console.WriteLine($"客户端 #{clientId} 的已断开连接");
            jsonRpc.Dispose();
            await stream.DisposeAsync();
        }
    }

    public class GreeterServer
    {
        public string SayHello(string name)
        {
            Console.WriteLine($"收到【{name}】的问好,并回复了他");
            return $"您好,{name}!";
        }
    }
}

客户端

与服务器端相似,我们在连接到服务器后获取TcpClient对象的Stream传入Attach函数即可,具体代码如下:

using StreamJsonRpc;
using System;
using System.IO.Pipes;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace StreamSample.Client
{
    class Program
    {
        static string GetMachineNameFromIPAddress(string ipAddress)
        {
            string machineName = null;
            try
            {
                IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
                machineName = hostEntry.HostName;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return machineName;
        }

        static string GetIPAddressFromMachineName(string machineName)
        {
            string ipAdress = string.Empty;
            try
            {
                IPAddress[] ipAddresses = Dns.GetHostAddresses(machineName);

                IPAddress ip = ipAddresses[1];

                ipAdress = ip.ToString();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
            }
            return ipAdress;
        }

        static async Task Main(string[] args)
        {
            TcpClient tcpClient = new TcpClient("192.168.31.67", 6600);
            var stream = tcpClient.GetStream();

            Console.WriteLine("正在连接服务器...");
            Console.WriteLine("已建立连接!");

            Console.WriteLine("我是精致码农,开始向服务端问好...");
            var jsonRpc = JsonRpc.Attach(stream);
            var message = await jsonRpc.InvokeAsync<string>("SayHello", "精致码农");
            Console.WriteLine($"来自服务端的响应:{message}");

            Console.ReadKey();
        }
    }
}

程序运行效果

服务器端
客户端

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sdhongjun

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值