Proto.Actor中提供了基于tcp/ip的通迅来实现Remote,可以通过其Remot实现对Actor的调用。
先来看一个极简单片的远程调用。
码友看码:
引用NuGet包
Proto.Actor
Proto.Remote
Proto.Serialization.Wire
共享库:
namespace P009_Lib
{
public class HelloRequest
{
public string Message
{
get; set;
}
}
public class HelloResponse
{
public string Message
{ get; set; }
}
}
服务端:
using P009_Lib;
using Proto;
using Proto.Remote;
using Proto.Serialization.Wire;
using System; using System.Threading;
using System.Threading.Tasks; namespace P009_Server
{
class Program
{
static void Main(string[] args)
{
Console.Title = "服务端";
Console.WriteLine("回车开始");
Console.ReadLine();
//设置序列化类型并注册
var wire = new WireSerializer(new[] { typeof(HelloRequest), typeof(HelloResponse) });
Serialization.RegisterSerializer(wire, true); var props = Actor.FromProducer(() => new HelloQuestActor());
//注册一个为hello类别的
Remote.RegisterKnownKind("hello", props);
//服务端监控端口5001
Remote.Start("127.0.0.1", );
Console.WriteLine("服务端开始……");
Console.ReadLine();
}
} class HelloQuestActor : IActor
{
public Task ReceiveAsync(IContext context)
{
switch (context.Message)
{
case HelloRequest msg:
Console.WriteLine(msg.Message);
context.Respond(new HelloResponse
{
Message = $"回应:我是服务端【{DateTime.Now}】",
});
break;
}
return Actor.Done;
}
}
}
客户端:
using P009_Lib;
using Proto;
using Proto.Remote;
using Proto.Serialization.Wire;
using System;
using System.Threading.Tasks; namespace P009_Client
{
class Program
{
static void Main(string[] args)
{ Console.Title = "客户端";
Console.WriteLine("回车开始");
Console.ReadLine();
//设置序列化类型并注册
var wire = new WireSerializer(new[] { typeof(HelloRequest), typeof(HelloResponse) });
Serialization.RegisterSerializer(wire, true);
//设置自己监控端口5002
Remote.Start("127.0.0.1", );
//连接服务端5001
var pid = Remote.SpawnNamedAsync("127.0.0.1:5001", "clientActor", "hello", TimeSpan.FromSeconds()).Result.Pid;
while (true)
{
var res = pid.RequestAsync<HelloResponse>(new HelloRequest { Message = $"请求:我是客户端 【{DateTime.Now}】" }).Result;
Console.WriteLine(res.Message);
Console.ReadLine();
}
}
}
}
代码很简单,看注释就够了。
……