看到這篇文章的題目,估計不少人都會問,這個組件是否是有些顯的無聊了,說到web通訊,不少人都會想到ASP.NET SignalR,或者Nodejs等等,實現web的網絡實時通信。有關於web實時通訊的相關概念問題,在這裏就再也不作具體的介紹了,有興趣的能夠自行百度。web
下面咱們介紹一款WebSocket組件websocket-sharp的相關內容。安全
一.websocket-sharp組件概述服務器
websocket-sharp是一個C#實現websocket協議客戶端和服務端,websocket-sharp支持RFC 6455;WebSocket客戶端和服務器;消息壓縮擴展;安全鏈接;HTTP身份驗證;查詢字符串,起始標題和Cookie;經過HTTP代理服務器鏈接;.NET Framework 3.5或更高版本(包括兼容環境,如Mono)。websocket
websocket-sharp是一個單一的組件,websocket-sharp.dll。websocket-sharp是用MonoDevelop開發的。因此創建一個簡單的方式是打開websocket-sharp.sln並使用MonoDevelop中的任何構建配置(例如Debug)運行websocket-sharp項目的構建。cookie
上面介紹了.NET項目中添加websocket-sharp組件,若是想向Unity項目中使用該DLL ,則應將其添加到Unity Editor中的項目的任何文件夾。在Unity的項目中,Unity Free有一些約束:Webplayer的安全沙箱(Web Player中不提供該服務器);WebGL網絡( WebGL中不可用);不適用於此類UWP;對System.IO.Compression的有限支持(壓縮擴展在Windows上不可用);iOS / Android的.NET Socket支持(若是您的Unity早於Unity 5,則須要iOS / Android Pro);適用於iOS / Android的.NET API 2.0兼容級別。適用於iOS / Android的.NET API 2.0兼容性級別可能須要在.NET 2.0以後修復缺乏某些功能,例如System.Func<...>代理(所以我已將其添加到該資產包中)。網絡
二.websocket-sharp組件使用方法併發
1.WebSocket客戶端框架
using System; using WebSocketSharp; namespace Example { public class Program { public static void Main (string[] args) { using (var ws = new WebSocket ("ws://dragonsnest.far/Laputa")) { ws.OnMessage += (sender, e) => Console.WriteLine ("Laputa says: " + e.Data); ws.Connect (); ws.Send ("BALUS"); Console.ReadKey (true); } } } }
由上面的代碼示例中,使用WebSocketWebSocket URL 建立類的新實例來鏈接。一個WebSocket.OnOpen當WebSocket鏈接已經創建發生的事件。WebSocket.OnMessage當發生事件WebSocket接收消息。一個WebSocket.OnClose當WebSocket的鏈接已關閉發生的事件。若是要異步鏈接到服務器,應該使用該WebSocket.ConnectAsync ()方法。可使用WebSocket.Send (string),WebSocket.Send (byte[])或WebSocket.Send (System.IO.FileInfo)方法來發送數據。若是您想要異步發送數據,則應該使用該WebSocket.SendAsync方法。若是要明確地關閉鏈接,應該使用該WebSocket.Close方法。異步
2.WebSocket服務器socket
using System; using WebSocketSharp; using WebSocketSharp.Server; namespace Example { public class Laputa : WebSocketBehavior { protected override void OnMessage (MessageEventArgs e) { var msg = e.Data == "BALUS" ? "I've been balused already..." : "I'm not available now."; Send (msg); } } public class Program { public static void Main (string[] args) { var wssv = new WebSocketServer ("ws://dragonsnest.far"); wssv.AddWebSocketService<Laputa> ("/Laputa"); wssv.Start (); Console.ReadKey (true); wssv.Stop (); } } }
以經過建立繼承WebSocketBehavior該類的類定義任何WebSocket服務的行爲。能夠WebSocketServer經過使用WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string)或WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>)方法將任何WebSocket服務添加到服務的指定行爲和路徑。wssv.Start ();啓動WebSocket服務器。wssv.Stop (code, reason);中止WebSocket服務器。
3.消息壓縮
ws.Compression = CompressionMethod.Deflate;
4.HTTP身份驗證
ws.SetCredentials ("nobita", "password", preAuth);
5.經過HTTP代理服務器鏈接
var ws = new WebSocket ("ws://example.com"); ws.SetProxy ("http://localhost:3128", "nobita", "password");
三.websocket-sharp組件核心對象解析
1.WebSocket.Send():
private bool send (Opcode opcode, Stream stream) { lock (_forSend) { var src = stream; var compressed = false; var sent = false; try { if (_compression != CompressionMethod.None) { stream = stream.Compress (_compression); compressed = true; } sent = send (opcode, stream, compressed); if (!sent) error ("A send has been interrupted.", null); } catch (Exception ex) { _logger.Error (ex.ToString ()); error ("An error has occurred during a send.", ex); } finally { if (compressed) stream.Dispose (); src.Dispose (); } return sent; } }
使用WebSocket鏈接發送指定的數據,該方法存在多個重載版本,而且該方法也有異步實現。該方法返回一個布爾類型的參數,表示本次信息是否發送成功。該方法接受兩個參數,Opcode是一個枚舉類型,表示WebSocket框架類型。該枚舉類型值有Cont(等於數值0.表示連續幀),Text(至關於數值1.表示文本框),Binary(至關於數值2.表示二進制幀),Close(至關於數值8.表示鏈接關閉框架),Ping(至關於數值9.表示ping幀),Pong(至關於數值10.指示pong框)。stream表示一個流對象。該方法設置了鎖操做,防止併發時出現死鎖問題。不過看到代碼中對異常的捕獲仍是有些問題,該方法是直接捕獲exception異常,這樣會致使程序捕獲代碼塊中的全部異常,這樣會影響代碼的穩定性和代碼的可修復性,異常捕獲的最好處理方式是將程序進行恢復。
2.WebSocket.CloseAsync():
public void CloseAsync (CloseStatusCode code, string reason) { string msg; if (!CheckParametersForClose (code, reason, _client, out msg)) { _logger.Error (msg); error ("An error has occurred in closing the connection.", null); return; } closeAsync ((ushort) code, reason); }
該方法以指定的方式異步關閉WebSocket鏈接,該方法接受兩個參數,CloseStatusCode表示關閉緣由的狀態碼,該參數是一個枚舉類型。reason表示關閉的緣由。大小必須是123字節或更少。if (!CheckParametersForClose (code, reason, _client, out msg))檢查參數關閉。
3.WebSocket.createHandshakeRequest():
private HttpRequest createHandshakeRequest() { var ret = HttpRequest.CreateWebSocketRequest(_uri); var headers = ret.Headers; if (!_origin.IsNullOrEmpty()) headers["Origin"] = _origin; headers["Sec-WebSocket-Key"] = _base64Key; _protocolsRequested = _protocols != null; if (_protocolsRequested) headers["Sec-WebSocket-Protocol"] = _protocols.ToString(", "); _extensionsRequested = _compression != CompressionMethod.None; if (_extensionsRequested) headers["Sec-WebSocket-Extensions"] = createExtensions(); headers["Sec-WebSocket-Version"] = _version; AuthenticationResponse authRes = null; if (_authChallenge != null && _credentials != null) { authRes = new AuthenticationResponse(_authChallenge, _credentials, _nonceCount); _nonceCount = authRes.NonceCount; } else if (_preAuth) { authRes = new AuthenticationResponse(_credentials); } if (authRes != null) headers["Authorization"] = authRes.ToString(); if (_cookies.Count > 0) ret.SetCookies(_cookies); return ret; }
該方法用於客戶端建立一個websocket請求,建立握手請求。var ret = HttpRequest.CreateWebSocketRequest(_uri);根據傳入的uri調用HttpRequest的方法建立請求。該方法主要操做http頭部信息,建立請求。
四.總結
對於這個組件,我的感受仍是有一些用,這個組件很好的實現了websocket,這裏也只是簡單的介紹,須要使用的同窗,能夠自取,由於該組件是開源的,因此一些實際狀況中能夠自行修改源碼,達到最大限度的擴展性。在項目的技術選擇中,我的比較主張開源免費的框架和組件,不只是項目預算的問題,更有方便擴展的做用。
********轉載:https://m.jb51.net/article/111064.htm