(點擊上方藍字,可快速關注我們)
來源:伯樂在線專欄作者 - 彭澤
cnblogs.com/pengze0902/p/6697192.html
看到這篇博客的題目,估計很多人都會問,這個組件是不是有些顯的無聊了,說到web通信,很多人都會想到ASP.NET SignalR,或者Nodejs等等,實現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-sharp是一個單一的組件,websocket-sharp.dll。websocket-sharp是用MonoDevelop開發的。所以建立一個簡單的方式是打開websocket-sharp.sln並使用MonoDevelop中的任何構建配置(例如Debug)運行websocket-sharp項目的構建。
上面介紹了.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伺服器
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,這裡也只是簡單的介紹,需要使用的同學,可以自取,因為該組件是開源的,所以一些實際情況中可以自行修改源碼,達到最大限度的擴展性。在項目的技術選擇中,個人比較主張開源免費的框架和組件,不僅是項目預算的問題,更有方便擴展的作用。
看完本文有收穫?請轉發分享給更多人
關注「DotNet」,提升.Net技能