Skip to main content

定义、发布、启动服务

一、定义服务

服务器端中新建一个类,继承于RpcServer类(或实现IRpcServer),然后在该类中写公共方法,并用JsonRpc属性标签标记,如果方法有重载,需要重新指定函数键

  • 支持代理生成注释
public class JsonRpcServer : RpcServer
{
[JsonRpc]
public string TestJsonRpc(string str)
{
return "TouchSocket" + str;
}

/// <summary>
/// 当标记为true时直接使用方法名称
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
[JsonRpc(true)]
public string TestJsonRpc1(string str)
{
return "TouchSocket" + str;
}

/// <summary>
/// 使用调用上下文。
/// 可以从上下文获取调用的SocketClient。从而获得IP和Port等相关信息。
/// </summary>
/// <param name="callContext"></param>
/// <param name="str"></param>
/// <returns></returns>
[JsonRpc(MethodFlags = MethodFlags.IncludeCallContext)]
public string TestGetContext(ICallContext callContext, string str)
{
if (callContext.Caller is HttpSocketClient)
{
Console.WriteLine("HTTP请求");
var client = callContext.Caller as HttpSocketClient;
var ip = client.IP;
var port = client.Port;
Console.WriteLine($"HTTP请求{ip}:{port}");

}

if (callContext.Caller is SocketClient)
{
Console.WriteLine("Tcp请求");
var client = callContext.Caller as SocketClient;
var ip = client.IP;
var port = client.Port;

client.Send(Encoding.UTF8.GetBytes("Hello Word"));
Console.WriteLine($"Tcp请求{ip}:{port}");

}
return "TouchSocket" + str;
}

[JsonRpc]
public JObject TestJObject(JObject obj)
{
return obj;
}
}

二、使用Tcp创建服务解析器

服务解析器是实际的服务接收、触发、调用、反馈的实际载体,通俗来说就是通信服务器

JsonRpcParserPlugin插件添加在TcpService服务器时,会使用TCP协议。此时的调用,会根据适配器类型,决定是否需要有调用结束标识,一般以\r\n结尾。

TcpService service = new TcpService();
service.Setup(new TouchSocketConfig()
.UsePlugin()
.ConfigureRpcStore(a =>
{
a.RegisterServer<JsonRpcServer>();//配置RpcStore必须在最前面。
})
.ConfigurePlugins(a =>
{
a.Add<JsonRpcParserPlugin>();//tcp中路由路径无效
})
.SetDataHandlingAdapter(() =>
{
return new NormalDataHandlingAdapter();
//return new TerminatorPackageAdapter("\r\n");使用该适配器时,调用方必须在最后追加相应的结束调用符。
})
.SetListenIPHosts(new IPHost[] { new IPHost(7705) }))
.Start();

三、使用Http或Websocket创建服务解析器

JsonRpcParserPlugin插件添加在HttpService服务器时,会使用Http、Websocket协议。

创建后,如果想使用Http调用,只需要以Post方式,将调用Json字符串路由到设定路由地址即可(下文示例“/jsonRpc”)。 如果想使用Websocket调用,只需要以文本形式,传递到服务器即可。服务器会判定:如果内容中包含“jsonrpc”则认定为调用,会做调用处理。

HttpService service = new HttpService();

service.Setup(new TouchSocketConfig()
.UsePlugin()
.SetListenIPHosts(new IPHost[] { new IPHost(7706) })
.ConfigureRpcStore(a =>//Rpc的配置必须在插件之前。
{
a.RegisterServer<JsonRpcServer>();
})
.ConfigurePlugins(a =>
{
a.Add<WebSocketServerPlugin>()
.SetWSUrl("/ws");//启用websocket,使用/ws路由连接。

a.Add<JsonRpcParserPlugin>()
.SetJsonRpcUrl("/jsonRpc");
}))
.Start();