金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks
# Unity使用异步grpc

(金庆的专栏 2020.6)

Unity 保证 async 方法运行在主线程中,所以用异步方式调用 grpc 可以大大简化网络通信的代码。

以下示例中将 grpc 的 RouteGuide 示例移到 Unity 中运行。
https://github.com/grpc/grpc/tree/master/examples/csharp/RouteGuide

其中 Main() 中的代码移到 Start() 中运行,阻塞调用改成异步调用, GetFeature() 改成 GetFeatureAsync()。

完整代码见:https://gitee.com/jinq0123/unity-grpc-async

```
using Grpc.Core;
using Routeguide;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using static Routeguide.Program;

public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    async void Start()
    {
        var channel = new Channel("127.0.0.1:50052", ChannelCredentials.Insecure);
        var client = new RouteGuideClient(new RouteGuide.RouteGuideClient(channel));

        // Looking for a valid feature
        await client.GetFeatureAsync(409146138, -746188906);

        // Feature missing.
        await client.GetFeatureAsync(0, 0);

        // Looking for features between 40, -75 and 42, -73.
        await client.ListFeatures(400000000, -750000000, 420000000, -730000000);

        // Record a few randomly selected points from the features file.
        await client.RecordRoute(RouteGuideUtil.LoadFeatures(), 10);

        // Send and receive some notes.
        await client.RouteChat();

        await channel.ShutdownAsync();

        Debug.Log("End of test.");
    }
}
```
posted on 2020-06-22 15:19 金庆 阅读(607) 评论(0)  编辑 收藏 引用 所属分类: 9. 其它2. 网游开发

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理