Open-source C # implements WebSocket protocol client and server websocket-sharp component parsing,

Source: Internet
Author: User
Tags http authentication unity 5

Open-source C # implements WebSocket protocol client and server websocket-sharp component parsing,

I haven't written a blog for a long time (at least I feel I haven't written it for a long time). I can't help it. The landlord is also a person who needs to live. I 've been looking for a job for a long time. (People who urge me to write code all day long hope to understand more. I will stick to writing our projects and still need to trust me. After all, this is a time-consuming and labor-consuming thing, things that all participants need to stick .)

After the above nonsense is completed, the following shows our overall situation. Many people may ask if this component is boring. When it comes to web communication, many people will think of ASP. NET SignalR, or Nodejs, to implement real-time web communication. There are questions about the concept of real-time web communication, so I will not introduce them here. If you are interested, you can use Baidu.

The following describes the content of a WebSocket component websocket-sharp.

1. Overview of websocket-sharp Components

Websocket-sharp is a C # client and server that implements the websocket protocol. websocket-sharp supports RFC 6455, WebSocket client and server, message compression extension, secure connection, HTTP authentication, and query string, start title and Cookie; Connect via HTTP Proxy Server ;.. NET Framework 3.5 or later (including compatible environments such as Mono ).

Websocket-sharp is a single component, websocket-sharp.dll. Websocket-sharp is developed using MonoDevelop. So an easy way to build is to open the websocket-sharp.sln and use any build configuration in MonoDevelop (for exampleDebug) Run the construction of the websocket-sharp project.

The preceding section describes how to add the websocket-sharp component to the. NET project. To use this DLL in the Unity project, add it to any folder of the project in the Unity Editor. In Unity projects, Unity Free has some constraints: the Security Sandbox of Webplayer (this server is not provided in Web Player); WebGL Network (unavailable in WebGL); not applicable to such UWP; for System. IO. limited support for Compression (Compression extension is not available on Windows); for iOS/Android. NET Socket support (If your Unity is earlier than Unity 5, iOS/Android Pro is required); applicable to iOS/Android.. net api 2.0 compatibility level. For iOS/Android, the. net api 2.0 compatibility level may need to be fixed after. NET 2.0. For exampleSystem.Func<...>Proxy (so I have added it to this asset package ).

Ii. websocket-sharp component usage

1. WebSocket Client

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

In the preceding code exampleWebSocketWebSocket URL creates a new instance of the class to connect. OneWebSocket.OnOpenEvents that occur when a WebSocket connection is established.WebSocket.OnMessageWhen an event occursWebSocketReceive messages. OneWebSocket.OnCloseEvents that occur when the WebSocket connection is closed. If you want to connect to the server asynchronously, useWebSocket.ConnectAsync ()Method. AvailableWebSocket.Send (string),WebSocket.Send (byte[])OrWebSocket.Send (System.IO.FileInfo)Method to send data. If you want to send data asynchronously, useWebSocket.SendAsyncMethod. To explicitly close the connection, useWebSocket.CloseMethod.

2. WebSocket Server

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

To create an inheritanceWebSocketBehaviorThis class defines any WebSocket service behavior. YesWebSocketServerUseWebSocketServer.AddWebSocketService<TBehaviorWithNew> (string)OrWebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>)Method to add any WebSocket service to the specified behavior and path of the service. Wssv. Start (); Start the WebSocket server. Wssv. Stop (code, reason); Stop the WebSocket server.

3. Message Compression

ws.Compression = CompressionMethod.Deflate;

 4. HTTP Authentication

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

5. connect through the HTTP Proxy Server

var ws = new WebSocket ("ws://example.com");ws.SetProxy ("http://localhost:3128", "nobita", "password");
Iii. Analysis of core objects of websocket-sharp Components

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

Use WebSocket connection to send specified data. This method has multiple overloaded versions, and this method also has asynchronous implementation. This method returns a Boolean parameter indicating whether the message is successfully sent. This method accepts two parameters. Opcode is an enumeration type, indicating the WebSocket framework type. This enumeration type value has Cont (equal to the value 0. continuous Frame), Text (equivalent to the value 1. text Box), Binary (equivalent to the value 2. binary frame), Close (equivalent to the value 8. indicates that the connection is closed.) Ping (equivalent to the value 9. ping frame), Pong (equivalent to the value 10. pong box ). Stream indicates a stream object. This method sets the lock operation to prevent deadlock during concurrency. However, there are still some problems with exception capture in the Code. This method directly captures exception exceptions, which will cause the program to capture all exceptions in the code block, this will affect the code stability and code maintainability. The best way to handle exception capture is to restore the program.

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

This method asynchronously closes the WebSocket connection in the specified way. This method accepts two parameters. CloseStatusCode indicates the status code of the reason for closing. this parameter is an enumeration type. Reason indicates the reason for disabling. The size must be 123 bytes or less. If (! CheckParametersForClose (code, reason, _ client, out msg) check if the parameter is disabled.

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

This method is used by the client to create a websocket request and a handshake request. Var ret = HttpRequest. CreateWebSocketRequest (_ uri); call the HttpRequest method to create a request based on the input uri. This method mainly deals with http header information and creates requests.

Iv. Summary

For this component, I personally feel that it is still useful. This component is a good implementation of websocket. It is just a brief introduction here. You can use it yourself, because this component is open-source, you can modify the source code to maximize scalability in some actual situations. In the technical selection of projects, I personally advocate open-source free frameworks and components, which are not only a problem of project budget, but also facilitate expansion.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.