定义服务

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

  • 支持代理生成注释。 ```csharp public class Server : ServerProvider { [WebApi(HttpMethodType.GET)] public int Sum(int a, int b) {

    1. return a + b;

    }

    [WebApi(HttpMethodType.POST)] public int TestPost(MyClass myClass) {

    1. return myClass.A + myClass.B;

    }

    ///

    /// 使用调用上下文,响应文件下载。 /// /// [WebApi(HttpMethodType.GET, MethodFlags = MethodFlags.IncludeCallContext)] public Task DownloadFile(WebApiServerCallContext callContext,string id) {

    1. if (id=="rrqm")
    2. {
    3. callContext.Context.Response.FromFile(@"D:\System\Windows.iso", callContext.Context.Request);
    4. return Task.FromResult("ok");
    5. }
    6. return Task.FromResult("id不正确。");

    } }

public class MyClass { public int A { get; set; } public int B { get; set; } }

  1. <a name="lHhEB"></a>
  2. ## 创建简单服务器
  3. ```csharp
  4. static void Main(string[] args)
  5. {
  6. HttpService service = new HttpService();
  7. service.Setup(new RRQMConfig()
  8. .UsePlugin()
  9. .SetListenIPHosts(new IPHost[] { new IPHost(7789) }))
  10. .Start();
  11. service.Logger.Message("服务器已启动");
  12. WebApiParserPlugin parserPlugin= service.AddPlugin<WebApiParserPlugin>();
  13. parserPlugin.RegisterServer<Server>();//给插件注册服务。
  14. service.Logger.Message("使用:http://127.0.0.1:7789/Server/Sum?a=10&b=20");
  15. }

创建联和服务解析器

联和服务解析可以和TouchRpc,XmlRpc等合并创建,共用RpcStore。

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

  1. private static IRpcParser CreateWebApiParser()
  2. {
  3. HttpService service = new HttpService();
  4. service.Setup(new RRQMConfig()
  5. .UsePlugin()
  6. .SetListenIPHosts(new IPHost[] { new IPHost(7789) }))
  7. .Start();
  8. return service.AddPlugin<WebApiParserPlugin>();
  9. }

注册、发布服务

添加解析器(添加时需要以键、值方式添加,方便后续查找),然后注册服务即可。

  1. static void Main(string[] args)
  2. {
  3. RpcStore rpcStore = new RpcStore();
  4. rpcStore.AddRpcParser("webApiParser", CreateWebApiParser());
  5. rpcStore.RegisterServer<Server>();//注册服务
  6. Console.WriteLine("以下连接用于测试webApi");
  7. Console.WriteLine($"使用:http://127.0.0.1:7789/Server/Sum?a=10&b=20");
  8. RpcStore.ProxyAttributeMap.TryAdd("webapi",typeof(WebApiAttribute));
  9. //生成的WebApi的本地代理文件。
  10. //ServerCellCode[] cellCodes = rpcStore.GetProxyInfo(RpcStore.ProxyAttributeMap.Values.ToArray());
  11. //当想导出全部时,RpcStore.ProxyAttributeMap.Values.ToArray()
  12. //string codeString = CodeGenerator.ConvertToCode("RRQMProxy", cellCodes);
  13. rpcStore.ShareProxy(new IPHost(8848));//分享远程代理
  14. Console.ReadKey();
  15. }