Unity使用TouchSocket的RPC

服务器端

使用.NET版本为:4.6.2

安装包:TouchSocket.Dmtp

csharp 复制代码
    public partial class MyRpcServer : SingletonRpcServer
    {
        [DmtpRpc(MethodInvoke = true)]
        public int Add(int a, int b)
        {
            Console.WriteLine("调用Add");
            var sum = a + b;
            return sum;
        }
    }


    internal class Program
    {
        static async Task Main(string[] args)
        {
            var service = new TcpDmtpService();
            var config = new TouchSocketConfig()//配置
                   .SetListenIPHosts(7789)
                   .ConfigureContainer(a =>
                   {
                       a.AddDmtpRouteService();
                       //添加Rpc注册器
                       a.AddRpcStore(store =>
                       {
                           store.RegisterServer<MyRpcServer>();//注册服务
                       });

                   })
                   .ConfigurePlugins(a =>
                   {
                       //启用DmtpRpc功能
                       a.UseDmtpRpc();
                       a.Add<ConnectedPlugin>();
                       a.Add<ClosedPlugin>();
                       a.Add<MyRpcPlugin>();
                   })
                   .SetDmtpOption(options =>
                   {
                       options.VerifyToken = "Dmtp";//设定连接口令,作用类似账号密码
                       options.VerifyTimeout = TimeSpan.FromSeconds(3);//设定验证超时时间为3秒
                   });

            await service.SetupAsync(config);

            await service.StartAsync();
            Console.WriteLine("successed");

            Console.ReadLine();
        }

    }

    public class ConnectedPlugin : IDmtpConnectedPlugin
    {
        public bool DisposedValue => false;

        public void Dispose()
        {

        }

        public void Loaded(IPluginManager pluginManager)
        {

        }

        public Task OnDmtpConnected(IDmtpActorObject client, DmtpVerifyEventArgs e)
        {
            Console.WriteLine(client.DmtpActor.Id + ":连上了");
            return Task.CompletedTask;
        }

        public void Unloaded(IPluginManager pluginManager)
        {

        }
    }
    public class ClosedPlugin : IDmtpClosedPlugin
    {
        public bool DisposedValue => false;

        public void Dispose()
        {

        }

        public void Loaded(IPluginManager pluginManager)
        {

        }

        public Task OnDmtpClosed(IDmtpActorObject client, ClosedEventArgs e)
        {
            Console.WriteLine(client.DmtpActor.Id + ":断开了");
            return Task.CompletedTask;
        }

        public void Unloaded(IPluginManager pluginManager)
        {

        }
    }

    public class MyRpcPlugin : PluginBase, IDmtpRoutingPlugin
    {
        public async Task OnDmtpRouting(IDmtpActorObject client, PackageRouterEventArgs e)
        {
            if (e.RouterType == RouteType.Rpc)
            {
                e.IsPermitOperation = true;
                return;
            }

            await e.InvokeNext();
        }
    }

Unity端

群文件中下载Unity插件

导入Unity中

csharp 复制代码
public class NewMonoBehaviourScript : MonoBehaviour
{
    // Start is called once before the first execution of Update after the MonoBehaviour is created
    private TcpDmtpClient client1;
    async void Start()
    {

        client1 = new TcpDmtpClient();
        await client1.SetupAsync(new TouchSocketConfig()
              .ConfigureContainer(a =>
              {
                  a.AddConsoleLogger();
                  a.AddRpcStore(a => a.RegisterServer<MyClientRpcServer>());
              })
              .ConfigurePlugins(a =>
              {
                  //启用dmtp rpc插件
                  a.UseDmtpRpc();
                  a.UseReconnection<TcpDmtpClient>(a => a.UseSimple());
              })
              .SetRemoteIPHost("127.0.0.1:7789")
              .SetDmtpOption(options =>
              {
                  options.VerifyToken = "Dmtp";
                  options.Id = "20001";
              }));
        await client1.ConnectAsync();
    }
    async void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            var sum = await client1.GetDmtpRpcActor().InvokeTAsync<int>("Add", InvokeOption.WaitInvoke, 10, 1);
            Debug.Log(sum);
        }
        if (Input.GetKeyDown(KeyCode.A))
        {
            var aa = await client1.GetDmtpRpcActor().InvokeTAsync<int>("10001", "Sub1", InvokeOption.WaitInvoke, 10, 1);
            Debug.Log(aa);
        }
    }
    void OnDisable()
    {
        client1.CloseAsync();
        client1.Dispose();
    }
}

public partial class MyClientRpcServer : SingletonRpcServer
{
    [DmtpRpc(MethodInvoke = true)]
    public int Sub1(int a, int b)
    {
        Debug.Log("调用Sub");
        var sum = a - b;
        return sum;
    }
}
相关推荐
AC梦17 小时前
unity中如何将UI上的字高清显示
ui·unity
devmoon1 天前
快速了解兼容 Ethereum 的 JSON-RPC 接口
开发语言·网络·rpc·json·区块链·智能合约·polkadot
小贺儿开发1 天前
Unity3D 智慧城市管理平台
数据库·人工智能·unity·智慧城市·数据可视化
June bug2 天前
【领域知识】休闲游戏一次发版全流程:Google Play + Apple App Store
unity
星夜泊客2 天前
C# 基础:为什么类可以在静态方法中创建自己的实例?
开发语言·经验分享·笔记·unity·c#·游戏引擎
dzj20212 天前
PointerEnter、PointerExit、PointerDown、PointerUp——鼠标点击物体,则开始旋转,鼠标离开或者松开物体,则停止旋转
unity·pointerdown·pointerup
心前阳光2 天前
Unity 模拟父子关系
android·unity·游戏引擎
南墙上的石头2 天前
docker日常使用命令汇总
docker·容器·rpc
在路上看风景2 天前
26. Mipmap
unity
咸鱼永不翻身2 天前
Unity视频资源压缩详解
unity·游戏引擎·音视频