欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#實(shí)現(xiàn)WebSocket協(xié)議客戶端和服務(wù)器websocket sharp組件實(shí)例解析

 更新時(shí)間:2017年04月13日 09:52:51   作者:彭澤0902  
這篇文章主要介紹了C#實(shí)現(xiàn)WebSocket協(xié)議客戶端和服務(wù)器websocket sharp組件實(shí)例解析,包括websocket sharp組件的概念及使用方法,需要的朋友可以參考下

看到這篇文章的題目,估計(jì)很多人都會(huì)問(wèn),這個(gè)組件是不是有些顯的無(wú)聊了,說(shuō)到web通信,很多人都會(huì)想到ASP.NET SignalR,或者Nodejs等等,實(shí)現(xiàn)web的網(wǎng)絡(luò)實(shí)時(shí)通訊。有關(guān)于web實(shí)時(shí)通信的相關(guān)概念問(wèn)題,在這里就不再做具體的介紹了,有興趣的可以自行百度。

  下面我們介紹一款WebSocket組件websocket-sharp的相關(guān)內(nèi)容。

一.websocket-sharp組件概述

    websocket-sharp是一個(gè)C#實(shí)現(xiàn)websocket協(xié)議客戶端和服務(wù)端,websocket-sharp支持RFC 6455;WebSocket客戶端和服務(wù)器;消息壓縮擴(kuò)展;安全連接;HTTP身份驗(yàn)證;查詢字符串,起始標(biāo)題和Cookie;通過(guò)HTTP代理服務(wù)器連接;.NET Framework 3.5或更高版本(包括兼容環(huán)境,如Mono)。

    websocket-sharp是一個(gè)單一的組件,websocket-sharp.dll。websocket-sharp是用MonoDevelop開(kāi)發(fā)的。所以建立一個(gè)簡(jiǎn)單的方式是打開(kāi)websocket-sharp.sln并使用MonoDevelop中的任何構(gòu)建配置(例如Debug)運(yùn)行websocket-sharp項(xiàng)目的構(gòu)建。

    上面介紹了.NET項(xiàng)目中添加websocket-sharp組件,如果想向Unity項(xiàng)目中使用該DLL ,則應(yīng)將其添加到Unity Editor中的項(xiàng)目的任何文件夾。在Unity的項(xiàng)目中,Unity Free有一些約束:Webplayer的安全沙箱(Web Player中不提供該服務(wù)器);WebGL網(wǎng)絡(luò)( WebGL中不可用);不適用于此類UWP;對(duì)System.IO.Compression的有限支持(壓縮擴(kuò)展在Windows上不可用);iOS / Android的.NET Socket支持(如果您的Unity早于Unity 5,則需要iOS / Android Pro);適用于iOS / Android的.NET API 2.0兼容級(jí)別。適用于iOS / Android的.NET API 2.0兼容性級(jí)別可能需要在.NET 2.0之后修復(fù)缺少某些功能,例如System.Func<...>代理(因此我已將其添加到該資產(chǎn)包中)。

二.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 創(chuàng)建類的新實(shí)例來(lái)連接。一個(gè)WebSocket.OnOpen當(dāng)WebSocket連接已經(jīng)建立發(fā)生的事件。WebSocket.OnMessage當(dāng)發(fā)生事件WebSocket接收消息。一個(gè)WebSocket.OnClose當(dāng)WebSocket的連接已關(guān)閉發(fā)生的事件。如果要異步連接到服務(wù)器,應(yīng)該使用該WebSocket.ConnectAsync ()方法??梢允褂肳ebSocket.Send (string),WebSocket.Send (byte[])或WebSocket.Send (System.IO.FileInfo)方法來(lái)發(fā)送數(shù)據(jù)。如果您想要異步發(fā)送數(shù)據(jù),則應(yīng)該使用該WebSocket.SendAsync方法。如果要明確地關(guān)閉連接,應(yīng)該使用該WebSocket.Close方法。

    2.WebSocket服務(wù)器

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 ();
  }
 }
}

    以通過(guò)創(chuàng)建繼承WebSocketBehavior該類的類定義任何WebSocket服務(wù)的行為。可以WebSocketServer通過(guò)使用WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string)或WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>)方法將任何WebSocket服務(wù)添加到服務(wù)的指定行為和路徑。wssv.Start ();啟動(dòng)WebSocket服務(wù)器。wssv.Stop (code, reason);停止WebSocket服務(wù)器。

    3.消息壓縮

ws.Compression = CompressionMethod.Deflate;

    4.HTTP身份驗(yàn)證

ws.SetCredentials ("nobita", "password", preAuth);

    5.通過(guò)HTTP代理服務(wù)器連接

var ws = new WebSocket ("ws://example.com");
ws.SetProxy ("http://localhost:3128", "nobita", "password");

三.websocket-sharp組件核心對(duì)象解析

    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連接發(fā)送指定的數(shù)據(jù),該方法存在多個(gè)重載版本,并且該方法也有異步實(shí)現(xiàn)。該方法返回一個(gè)布爾類型的參數(shù),表示本次信息是否發(fā)送成功。該方法接受兩個(gè)參數(shù),Opcode是一個(gè)枚舉類型,表示W(wǎng)ebSocket框架類型。該枚舉類型值有Cont(等于數(shù)值0.表示連續(xù)幀),Text(相當(dāng)于數(shù)值1.表示文本框),Binary(相當(dāng)于數(shù)值2.表示二進(jìn)制幀),Close(相當(dāng)于數(shù)值8.表示連接關(guān)閉框架),Ping(相當(dāng)于數(shù)值9.表示ping幀),Pong(相當(dāng)于數(shù)值10.指示pong框)。stream表示一個(gè)流對(duì)象。該方法設(shè)置了鎖操作,防止并發(fā)時(shí)出現(xiàn)死鎖問(wèn)題。不過(guò)看到代碼中對(duì)異常的捕獲還是有些問(wèn)題,該方法是直接捕獲exception異常,這樣會(huì)導(dǎo)致程序捕獲代碼塊中的所有異常,這樣會(huì)影響代碼的穩(wěn)定性和代碼的可修復(fù)性,異常捕獲的最好處理方式是將程序進(jìn)行恢復(fù)。

    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);
  }

    該方法以指定的方式異步關(guān)閉WebSocket連接,該方法接受兩個(gè)參數(shù),CloseStatusCode表示關(guān)閉原因的狀態(tài)碼,該參數(shù)是一個(gè)枚舉類型。reason表示關(guān)閉的原因。大小必須是123字節(jié)或更少。if (!CheckParametersForClose (code, reason, _client, out msg))檢查參數(shù)關(guān)閉。

    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;
    }

     該方法用于客戶端創(chuàng)建一個(gè)websocket請(qǐng)求,創(chuàng)建握手請(qǐng)求。var ret = HttpRequest.CreateWebSocketRequest(_uri);根據(jù)傳入的uri調(diào)用HttpRequest的方法創(chuàng)建請(qǐng)求。該方法主要操作http頭部信息,創(chuàng)建請(qǐng)求。

四.總結(jié)

   對(duì)于這個(gè)組件,個(gè)人感覺(jué)還是有一些用,這個(gè)組件很好的實(shí)現(xiàn)了websocket,這里也只是簡(jiǎn)單的介紹,需要使用的同學(xué),可以自取,因?yàn)樵摻M件是開(kāi)源的,所以一些實(shí)際情況中可以自行修改源碼,達(dá)到最大限度的擴(kuò)展性。在項(xiàng)目的技術(shù)選擇中,個(gè)人比較主張開(kāi)源免費(fèi)的框架和組件,不僅是項(xiàng)目預(yù)算的問(wèn)題,更有方便擴(kuò)展的作用。

以上所述是小編給大家介紹的C#實(shí)現(xiàn)WebSocket協(xié)議客戶端和服務(wù)器websocket-sharp組件實(shí)例解析,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論