准備
我們使用CookComputing.XmlRpcServerV2 3.0.0來構建XmlRpc服務器。
新建一個控制台項目,在項目中添加對CookComputing.XmlRpcServerV2 3.0.0的引用,可以使用nuget來安裝。
1 2 |
PM> Install-Package xmlrpcnet PM> Install-Package xmlrpcnet-server |
編寫服務
我這里寫了個非常簡單的服務,代碼如下:
1 2 3 4 5 6 7 8 |
public class SimpleService : XmlRpcListenerService { [XmlRpcMethod] public int Add(int a, int b) { return a + b; } } |
編寫Service Host相關代碼,也就是XmlRpc服務代碼
這里我們通過HttpListener類處理XmlRpc客戶端的請求,HttpListener使用的是異步處理,代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Program { private static XmlRpcListenerService _svc = new SimpleService(); static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://127.0.0.1:11000/"); listener.Start(); listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener); Console.ReadLine(); } static void ProcessRequest(IAsyncResult result) { HttpListener listener = result.AsyncState as HttpListener; // 結束異步操作 HttpListenerContext context = listener.EndGetContext(result); // 重新啟動異步請求處理 listener.BeginGetContext(new AsyncCallback(ProcessRequest), listener); try { Console.WriteLine("From: " + context.Request.UserHostAddress); // 處理請求 _svc.ProcessRequest(context); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } |
啟動程序后,打開瀏覽器訪問:http://127.0.0.1:11000/就可以看到如下的頁面,現在就可以調用XmlRpc服務了。