在目前一些桌面端展示系统的应用中,需要多个子系统窗口进行信息交换,对于部署在同一台电脑上的各个子系统,可以通过集成windows系统的消息传递方式进行消息传递,但是假如将各个子系统部署在不同的电脑上,这种实现方式就有一定的局限性,要涉及到网络中的不同电脑进行通信,.net提供了可以建一个小的http服务器,可以绑定计算机的端口进行通信,且提供了异步的实现方式,能实现无阻塞的消息通信。
具体实现: //启动一个监听, 并绑定端口,MSDN有详细参数说明 public bool StartListener(string[] prefixes) { bool isSuccess = false; if (HttpListener.IsSupported) { HttpListener listener = new HttpListener(); foreach (string s in prefixes) { listener.Prefixes.Add(s); } listener.Start(); var result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); isSuccess = true; //Console.WriteLine("Waiting for request to be processed asyncronously."); //result.AsyncWaitHandle.WaitOne(); //listener.Close(); } return isSuccess; } public void StopListener() { if (listener != null) { if (listener.IsListening) { listener.Stop(); } listener.Close(); } } //异步接收数据,并进行下一次的 private void ListenerCallback(IAsyncResult result) { HttpListener listener = (HttpListener)result.AsyncState; HttpListenerContext context = listener.EndGetContext(result); HttpListenerRequest request = context.Request; HttpListenerResponse response = context.Response; response.ContentType = "text/plain"; System.IO.Stream output = response.OutputStream; string responseString = "true"; try { if (MessageAction != null) { System.IO.Stream inputStream = request.InputStream; string resStr = string.Empty; if (inputStream.CanRead) { byte[] bytes = new byte[request.ContentLength64]; int numBytesToRead = (int)request.ContentLength64; inputStream.Read(bytes, 0, numBytesToRead); inputStream.Close(); resStr = Encoding.UTF8.GetString(bytes); } MessageAction(resStr); } } catch (Exception ex) { responseString = "false"; } byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString); response.ContentLength64 = buffer.Length; output.Write(buffer, 0, buffer.Length); output.Close(); result = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); }
将建立好的代码集成到应用程序里,使用.Net的webclient就可以进行消息的操作。
转载于:https://blog.51cto.com/speciallst/1835672