C# WebSocket通信

HttpListener创建的HTTP服务不能做到实时通信。所以需要WebScket实现与网页的通讯。

首先要在NuGet导入“Fleck”包,需 .NET Framework 4.5及以上。

 

 FleckLog.Level = LogLevel.Debug;
            var allSockets = new List<IWebSocketConnection>();
            var server = new WebSocketServer("ws://127.0.0.1:50000");
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {
                    //Console.WriteLine("Open!");
                    allSockets.Add(socket);
                };
                socket.OnClose = () =>
                {
                    //Console.WriteLine("Close!");
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    //Console.WriteLine(message);
                    allSockets.ToList().ForEach(s => s.Send("Echo: " + message));
                };
            });




            var input = DateTime.Now.ToString();
            while (input != "")
            {
                Thread.Sleep(1000);
                foreach (var socket in allSockets.ToList())
                {
                    socket.Send(input);
                }

                input = DateTime.Now.ToString();
            }

  2.html网页

<html>
<body>

    Welcome<br/>
    <input id="text" type="text" />
    <button onclick="send()">Send</button>
    <button onclick="closeWebSocket()">Close</button>
    <div id="message"></div>
    
</body>

<script type="text/JavaScript">
      var websocket = null;
      
      //判断当前浏览器是否支持WebSocket
      if(‘WebSocket‘ in window){
          websocket = new WebSocket("ws://localhost:50000");
      }
      else{
          alert(‘Not support websocket‘);
      }    
      //连接发生错误的回调方法
      websocket.onerror = function(){
          setMessageInnerHTML("error");
      };     
      //连接成功建立的回调方法
      websocket.onopen = function(event){
          setMessageInnerHTML("open");
      };      
      //接收到消息的回调方法
      websocket.onmessage = function(){
     console.log(event,‘receive‘)
          setMessageInnerHTML(event.data);
      };     
      //连接关闭的回调方法
      websocket.onclose = function(){
          setMessageInnerHTML("close");
      };       
      //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
      window.onbeforeunload = function(){
          websocket.close();
      };       
      //将消息显示在网页上
      function setMessageInnerHTML(innerHTML){
          document.getElementById(‘message‘).innerHTML += innerHTML + ‘<br/>‘;
      } 
      //关闭连接
      function closeWebSocket(){
          websocket.close();
      }  
      //发送消息
      function send(){
          var message = document.getElementById(‘text‘).value;
          websocket.send(message);
      }
  </script>


</html>

  3.运行程序,打开html网页,网页和服务实现消息的实时通讯,如下图

C#  WebSocket通信

 

C# WebSocket通信

上一篇:win10 visual studio 设置默认管理员权限启动


下一篇:Delphi - Format