C#(SuperWebSocket)與websocket通訊

原文: C#(SuperWebSocket)與websocket通訊

客戶端代碼

點擊能夠查看一些關於websocket的介紹javascript

 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服務器的網絡實現。html

 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             try
11             {
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了,由於它真的簡單實用高大上。直接在NuGet包中就能夠直接安裝,java

順帶把經常使用的log4net和njson都裝了,一步到位啊。web

相關文章
相關標籤/搜索