定义服务
在服务器端中新建一个类,继承于ServerProvider类(或实现IServerProvider),然后在该类中写公共方法,并用WebApi属性标签标记,如果方法有重载,需要重新指定函数键。
支持代理生成注释。 ```csharp public class Server : ServerProvider { [WebApi(HttpMethodType.GET)] public int Sum(int a, int b) {
return a + b;
}
[WebApi(HttpMethodType.POST)] public int TestPost(MyClass myClass) {
return myClass.A + myClass.B;
}
///
/// 使用调用上下文,响应文件下载。 /// /// [WebApi(HttpMethodType.GET, MethodFlags = MethodFlags.IncludeCallContext)] public TaskDownloadFile(WebApiServerCallContext callContext,string id) { if (id=="rrqm")
{
callContext.Context.Response.FromFile(@"D:\System\Windows.iso", callContext.Context.Request);
return Task.FromResult("ok");
}
return Task.FromResult("id不正确。");
} }
public class MyClass { public int A { get; set; } public int B { get; set; } }
<a name="lHhEB"></a>
## 创建简单服务器
```csharp
static void Main(string[] args)
{
HttpService service = new HttpService();
service.Setup(new RRQMConfig()
.UsePlugin()
.SetListenIPHosts(new IPHost[] { new IPHost(7789) }))
.Start();
service.Logger.Message("服务器已启动");
WebApiParserPlugin parserPlugin= service.AddPlugin<WebApiParserPlugin>();
parserPlugin.RegisterServer<Server>();//给插件注册服务。
service.Logger.Message("使用:http://127.0.0.1:7789/Server/Sum?a=10&b=20");
}
创建联和服务解析器
联和服务解析可以和TouchRpc,XmlRpc等合并创建,共用RpcStore。
服务解析器是实际的服务接收、触发、调用、反馈的实际载体,通俗来说就是通信服务器。
private static IRpcParser CreateWebApiParser()
{
HttpService service = new HttpService();
service.Setup(new RRQMConfig()
.UsePlugin()
.SetListenIPHosts(new IPHost[] { new IPHost(7789) }))
.Start();
return service.AddPlugin<WebApiParserPlugin>();
}
注册、发布服务
添加解析器(添加时需要以键、值方式添加,方便后续查找),然后注册服务
即可。
static void Main(string[] args)
{
RpcStore rpcStore = new RpcStore();
rpcStore.AddRpcParser("webApiParser", CreateWebApiParser());
rpcStore.RegisterServer<Server>();//注册服务
Console.WriteLine("以下连接用于测试webApi");
Console.WriteLine($"使用:http://127.0.0.1:7789/Server/Sum?a=10&b=20");
RpcStore.ProxyAttributeMap.TryAdd("webapi",typeof(WebApiAttribute));
//生成的WebApi的本地代理文件。
//ServerCellCode[] cellCodes = rpcStore.GetProxyInfo(RpcStore.ProxyAttributeMap.Values.ToArray());
//当想导出全部时,RpcStore.ProxyAttributeMap.Values.ToArray()
//string codeString = CodeGenerator.ConvertToCode("RRQMProxy", cellCodes);
rpcStore.ShareProxy(new IPHost(8848));//分享远程代理
Console.ReadKey();
}