C#(SuperWebSocket)与websocket通信

8/3/2015来源:C#应用人气:9026

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     }

刚开始自己也试着写了个websocket的服务器,但是觉得麻烦,后来还是直接用SuperWebSocket了(感谢作者kerryjiang),因为它真的很好用。直接在NuGet包中就可以直接安装,

顺带把常用的log4net和njson都装了,一步到位啊。

QQ/71OlfPu/7Pe8GFGhD/tay1L7mRCpfU+VrzErpayh9DYW3IffUZZ661F2XuGpi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