你的位置:首页 > ASP.net教程

[ASP.net教程]C#(SuperWebSocket)与websocket通信


客户端代码

点击可以查看一些关于websocket的介绍

 1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4   <meta charset="UTF-8"> 5   <title></title> 6 </head> 7 <body> 8 <input type="button" id="send" onclick="send()" value="发送"> 9 <input type="text" id="message">10 <script type="text/javascript">11   var wsClient=new WebSocket( 'ws://localhost:40001');12   wsClient.open=function(e){13     console.log("Connected!");14   }15   wsClient.onclose=function(e){16     console.log("Disconnected!");17   }18   wsClient.onmessage=function(e){19     console.log("接收消息:"+e.data);20   }21   wsClient.onerror=function(e){22     console.log(e.data);23   }24   function send(){25     var oText=document.getElementById("message");26     wsClient.send(oText.value);27   }28 </script>29 </body>30 </html>

服务器端代码

  SuperWebSocket  继承了Socket框架SuperSocket,是一个WebSocket服务器的网络实现。

 1   class Program 2   { 3     static void Main(string[] args) 4     { 5       WebSocketServer server = new WebSocketServer(); 6       server.NewSessionConnected += server_NewSessionConnected; 7  8       server.NewMessageReceived += server_NewMessageReceived; 9       server.SessionClosed += server_SessionClosed;10       try11       {12         server.Setup("127.0.0.1", 40001);//设置端口13         server.Start();//开启监听14       }15       catch (Exception ex)16       {17         Console.WriteLine(ex.Message);18       }19       Console.ReadKey();20     }21 22     static void server_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)23     {24       Console.WriteLine(session.Origin);25     }26 27     static void server_NewMessageReceived(WebSocketSession session, string value)28     {29       Console.WriteLine(value);30       session.Send(value);31     }32 33     static void server_NewSessionConnected(WebSocketSession session)34     {35       Console.WriteLine(session.Origin);36     }37   }