websocket-sharp

repository·master·Indexed 26 days ago

https://github.com/sta/websocket-sharp

A high-performance WebSocket library for .NET (supporting .NET Framework 3.5+ and Mono) that provides both client and server implementations. Compliant with RFC 6455, it includes support for secure connections (WSS), per-message compression (RFC 7692), HTTP authentication, and proxy server connectivity. The library allows for the creation of WebSocket servers, HTTP servers with WebSocket handshake support, and clients with customizable headers, cookies, and origin validation.

Tokens
2.5K
Snippets
8
Records
17
Agent score
41%

What's inside websocket-sharp

  1. Overview of websocket-sharp features

    master

    websocket-sharp is a .NET library (supporting .NET Framework 3.5+ and Mono) that provides WebSocket capabilities including:

    • RFC 6455 support
    • WebSocket Client and Server implementations
    • Per-message Compression extension
    • Secure Connection (WSS)
    • HTTP Authentication
    • Support for Query string, Origin header, Cookies, and User headers
    • Support for connecting through an HTTP proxy server
  2. Implement a WebSocket Server

    master

    To create a server, use the WebSocketServer class from the WebSocketSharp.Server namespace.

    1. Define Behavior: Create a class that inherits from WebSocketBehavior. Override OnMessage, OnOpen, OnError, or OnClose to handle logic. Use Send() to send data to a client or Sessions.Broadcast() to send to all clients.
    2. Initialize Server: Create a WebSocketServer instance with a port number. If no port is provided, it defaults to 80 (requires root/admin permissions).
    3. Add Services: Use AddWebSocketService<TBehavior>(string path) or AddWebSocketService<TBehavior>(string path, Action<TBehavior> init) to map paths to behaviors.
    4. Lifecycle: Call Start() to begin listening and Stop() to shut down.
    using System;
    using WebSocketSharp;
    using WebSocketSharp.Server;
    
    namespace Example
    {
      public class Laputa : WebSocketBehavior
      {
        protected override void OnMessage (MessageEventArgs e)
        {
          var msg = e.Data == "BALUS"
                    ? "Are you kidding?"
                    : "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 ();
        }
      }
    }
  3. Implement a WebSocket Client

    master

    To use websocket-sharp as a client, use the WebSocket class in the WebSocketSharp namespace. You can wrap the instance in a using block to ensure the connection is closed with status code 1001 (going away) when the block exits.

    Key steps:

    1. Instantiate WebSocket with a URL (e.g., ws:// or wss://).
    2. Subscribe to events: OnOpen, OnMessage, OnError, and OnClose.
    3. Call Connect() or ConnectAsync() to establish the connection.
    4. Use Send() or SendAsync() to transmit data.
    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);
          }
        }
      }
    }
  4. Install websocket-sharp via NuGet

    master

    You can install websocket-sharp using the NuGet Package Manager. Note that it is currently distributed as a prerelease version. Use the following command in the Package Manager Console:

    PM> Install-Package WebSocketSharp -Pre
  5. Install websocket-sharp by self-building

    master

    To use a self-built version of the library, add the compiled websocket-sharp.dll (e.g., from your /bin/Debug/ folder) to your project's library references.

    If you are using Unity, add the websocket-sharp.dll to any folder within your project, such as Assets/Plugins, using the Unity Editor.

  6. View websocket-sharp Examples

    master

    The repository contains several example projects demonstrating different usage patterns:

    • Example: A WebSocket client that connects to a server.
    • Example2: A standalone WebSocket server.
    • Example3: An HTTP server capable of accepting WebSocket handshake requests (useful for web browser testing).

    You can find these examples in the repository's Example, Example2, and Example3 directories.

  7. Configure Proxy Settings

    master

    To connect through an HTTP proxy, use ws.SetProxy(proxyUrl, username, password) before calling Connect().

    Note: If using Squid, ensure http_access deny CONNECT !SSL_ports is disabled in squid.conf to allow CONNECT requests.

    var ws = new WebSocket ("ws://example.com");
    ws.SetProxy ("http://localhost:3128", "nobita", "password");
  8. Build websocket-sharp from source

    master
    The project is developed with MonoDevelop and builds into a single assembly: websocket-sharp.dll. To build it yourself, open websocket-sharp.sln and run the build for the websocket-sharp project using any build configuration (e.g., Debug).
  9. Configure Secure Connections (SSL/TLS)

    master

    Client-side

    Use the wss:// scheme in the WebSocket URL. You can customize certificate validation via ws.SslConfiguration.ServerCertificateValidationCallback.

    Server-side

    Initialize WebSocketServer or HttpServer with the useSsl parameter set to true. Provide a certificate using wssv.SslConfiguration.ServerCertificate.

  10. Configure Logging

    master

    The WebSocket, WebSocketServer, and HttpServer classes provide built-in logging. You can adjust the logging level via the Log.Level property using the LogLevel enum. The default level is LogLevel.Error.

    Example of setting level to Debug and logging a message:

    ws.Log.Level = LogLevel.Debug;
    ws.Log.Debug("This is a debug message.");
    ws.Log.Level = LogLevel.Debug;
    ws.Log.Debug ("This is a debug message.");
  11. Handle Query Strings, Origin, Cookies, and Headers

    master

    Query Strings

    • Client: Include parameters in the URL: new WebSocket("ws://example.com/?name=nobita").
    • Server: Access via WebSocketBehavior.QueryString in the service class.

    Origin Header

    • Client: Set ws.Origin = "http://example.com".
    • Server: Validate via WebSocketServer.AddWebSocketService using the OriginValidator property on the behavior instance.

    Cookies

    • Client: Use ws.SetCookie(new Cookie("name", "value")).
    • Server: Respond to/modify cookies using the CookiesResponder property on the behavior.

    User Headers

    • Client: Send via ws.SetUserHeader("Key", "Value"). Read response headers via ws.HandshakeResponseHeaders["Key"].
    • Server: Respond to/set headers using the UserHeadersResponder property on the behavior.
  12. Configure HTTP Authentication

    master

    Client-side

    Use ws.SetCredentials(username, password, preAuth) before connecting. If preAuth is true, credentials are sent in the first handshake request (Basic). If false, they are sent in the second request (Basic or Digest).

    Server-side

    Set wssv.AuthenticationSchemes (e.g., AuthenticationSchemes.Basic or AuthenticationSchemes.Digest), define a wssv.Realm, and provide a wssv.UserCredentialsFinder delegate to validate credentials.