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;
    }
}
相关推荐
天人合一peng29 分钟前
Unity中做表头时像work中整个调整宽窄
unity
小李也疯狂12 小时前
Unity 中的立方体贴图(Cubemaps)
unity·游戏引擎·贴图·cubemap
牛掰是怎么形成的12 小时前
Unity材质贴图引用陷阱:包体暴涨真相
unity·材质·贴图
呆呆敲代码的小Y12 小时前
【Unity工具篇】| 超实用工具LuBan,快速上手使用
游戏·unity·游戏引擎·unity插件·luban·免费游戏·游戏配置表
EQ-雪梨蛋花汤12 小时前
【Unity优化】Unity多场景加载优化与资源释放完整指南:解决Additive加载卡顿、预热、卸载与内存释放问题
unity·游戏引擎
我的offer在哪里13 小时前
用 Unity 从 0 做一个「可以玩的」游戏,需要哪些步骤和流程
游戏·unity·游戏引擎
泡泡茶壶ᐇ14 小时前
Unity游戏开发入门指南:从零开始理解游戏引擎核心概念
unity·游戏引擎
YigAin15 小时前
Unity中的Lock,到底在锁什么,什么时候该用?
unity
Var_al16 小时前
抖小Unity WebGL分包命令行工具实践指南
unity·游戏引擎·webgl
天人合一peng17 小时前
unity 通过代码修改button及其名字字体的属性
unity·游戏引擎