### Start WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Starts the WebSocket server to begin accepting connections. ```csharp wssv.Start (); ``` -------------------------------- ### Create and Start WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Set up and start a WebSocket server. This involves defining a WebSocket service class inheriting from WebSocketBehavior and configuring the server with a specific path. ```csharp 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"); wssv.Start (); Console.ReadKey (true); wssv.Stop (); } } } ``` -------------------------------- ### Basic WebSocket Client Example Source: https://github.com/sta/websocket-sharp/blob/master/README.md A simple example demonstrating how to create a WebSocket client, connect to a server, send a message, and receive messages. ```csharp 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); } } } } ``` -------------------------------- ### WebSocket Server - Basic Setup Source: https://github.com/sta/websocket-sharp/blob/master/README.md Sets up a basic WebSocket server using WebSocketSharp.Server.WebSocketServer. ```APIDOC ## WebSocket Server Setup ### Description This example demonstrates how to set up a WebSocket server that hosts a specific WebSocket service. ### Code Example ```csharp 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"); wssv.Start (); Console.ReadKey (true); wssv.Stop (); } } } ``` ``` -------------------------------- ### Install websocket-sharp via NuGet Source: https://github.com/sta/websocket-sharp/blob/master/README.md Use this command in the Package Manager Console to install the prerelease version of websocket-sharp. ```csharp PM> Install-Package WebSocketSharp -Pre ``` -------------------------------- ### Starting and Stopping the WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Provides the methods for starting and stopping the WebSocket server. ```APIDOC ## Starting and Stopping the WebSocket Server ### Description These methods are used to control the lifecycle of the WebSocket server. ### Method `WebSocketServer.Start()` `WebSocketServer.Stop()` ### Request Example ```csharp // Starting the server wssv.Start (); // Stopping the server wssv.Stop (); ``` ``` -------------------------------- ### Setting up a WebSocketServer with Multiple Services Source: https://context7.com/sta/websocket-sharp/llms.txt Configure and start a WebSocket server that routes requests to different services based on the path. Supports basic authentication and service initialization. ```csharp using System; using System.Security.Cryptography.X509Certificates; using WebSocketSharp; using WebSocketSharp.Net; using WebSocketSharp.Server; // --- Service definitions --- public class EchoService : WebSocketBehavior { protected override void OnOpen() => Console.WriteLine("Echo: client connected, ID=" + ID); protected override void OnMessage(MessageEventArgs e) => Send(e.Data); protected override void OnError(ErrorEventArgs e) => Console.WriteLine("Echo error: " + e.Message); protected override void OnClose(CloseEventArgs e) => Console.WriteLine("Echo closed: " + e.Code); } public class ChatService : WebSocketBehavior { private string _nick; protected override void OnOpen() { _nick = QueryString["nick"] ?? "anon"; Sessions.Broadcast($">> {_nick} joined"); } protected override void OnMessage(MessageEventArgs e) => Sessions.Broadcast($"[{_nick}] {e.Data}"); protected override void OnClose(CloseEventArgs e) => Sessions.Broadcast($"<< {_nick} left"); } // --- Server setup --- class Program { static void Main() { var wssv = new WebSocketServer(4649); // Optional: secure server // var wssv = new WebSocketServer(5963, true); // wssv.SslConfiguration.ServerCertificate = // new X509Certificate2("/path/cert.pfx", "password"); // Basic authentication wssv.AuthenticationSchemes = AuthenticationSchemes.Basic; wssv.Realm = "ChatRealm"; wssv.UserCredentialsFinder = id => id.Name == "alice" ? new NetworkCredential("alice", "pass1", "admin") : null; // Register services wssv.AddWebSocketService("/echo"); wssv.AddWebSocketService("/chat"); // Service with initializer wssv.AddWebSocketService("/chat-bot", s => { s.OriginValidator = origin => !string.IsNullOrEmpty(origin) && origin.StartsWith("http://localhost"); s.IgnoreExtensions = false; }); wssv.Start(); Console.WriteLine($"WebSocket server started on ws://localhost:{wssv.Port}"); Console.WriteLine("Services: " + string.Join(", ", wssv.WebSocketServices.Paths)); Console.ReadKey(true); wssv.Stop(); } } ``` -------------------------------- ### Configure WebSocket Server HTTP Authentication Source: https://github.com/sta/websocket-sharp/blob/master/README.md Set up HTTP authentication schemes, realms, and user credential finders for a WebSocket server. This example shows configuration for Basic authentication. ```csharp wssv.AuthenticationSchemes = AuthenticationSchemes.Basic; wssv.Realm = "WebSocket Test"; wssv.UserCredentialsFinder = id => { var name = id.Name; // Return user name, password, and roles. return name == "nobita" ? new NetworkCredential (name, "password", "gunfighter") : null; // If the user credentials are not found. }; ``` -------------------------------- ### WebSocket Secure Connection (Server) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Explains how to configure a WebSocket server for secure connections using SSL/TLS, including certificate setup. ```APIDOC ## WebSocket Secure Connection (Server) ### Description This section describes how to set up a `WebSocketServer` or `HttpServer` to support secure connections using SSL/TLS. This involves providing an X.509 certificate. ### Method `new WebSocketServer(int port, bool secure)` constructor `WebSocketServer.SslConfiguration.ServerCertificate` property setter ### Parameters #### Request Body - **port** (int) - Required - The port number for the server. - **secure** (bool) - Required - Set to `true` to enable secure connections. - **ServerCertificate** (X509Certificate2) - Required - The server's SSL certificate, typically loaded from a PFX file. ### Request Example ```csharp var wssv = new WebSocketServer (5963, true); wssv.SslConfiguration.ServerCertificate = new X509Certificate2 ( "/path/to/cert.pfx", "password for cert.pfx" ); ``` ``` -------------------------------- ### Respond to User Headers in WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure a WebSocket server behavior to respond to incoming user headers during the handshake. This example shows how to extract a header value and set a response header. ```csharp wssv.AddWebSocketService ( "/Chat", s => { s.UserHeadersResponder = (reqHeaders, userHeaders) => { var val = reqHeaders["RequestForID"]; if (!val.IsNullOrEmpty ()) userHeaders[val] = s.ID; }; } ); ``` -------------------------------- ### Configure WebSocket Server Cookie Responder Source: https://github.com/sta/websocket-sharp/blob/master/README.md Set a response action for cookies on the server-side using `CookiesResponder`. This example iterates through received cookies, marks them as expired, and adds them to the response. ```csharp wssv.AddWebSocketService ( "/Chat", s => { s.CookiesResponder = (reqCookies, resCookies) => { foreach (var cookie in reqCookies) { cookie.Expired = true; resCookies.Add (cookie); } }; } ); ``` -------------------------------- ### WebSocket.SendAsync — Sending Data Asynchronously Source: https://context7.com/sta/websocket-sharp/llms.txt Details how to send data asynchronously without blocking the caller, using the `SendAsync` methods. Includes examples for text, binary data, files, and streams with callback notifications. ```APIDOC ## WebSocket.SendAsync — Sending Data Asynchronously `SendAsync(data, Action)` variants send data without blocking the caller. The `Action` callback receives `true` on success, `false` on failure; pass `null` to ignore the result. ```csharp using System; using System.IO; using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/echo")) { ws.OnMessage += (s, e) => Console.WriteLine("Echo: " + e.Data); ws.Connect(); // Async text send ws.SendAsync("Hello async!", sent => Console.WriteLine("Text sent: " + sent)); // Async binary send ws.SendAsync(new byte[] { 1, 2, 3, 4 }, sent => Console.WriteLine("Binary sent: " + sent)); // Async file send ws.SendAsync(new FileInfo("/tmp/image.png"), sent => Console.WriteLine("File sent: " + sent)); // Async stream send — reads exactly `length` bytes using (var fs = File.OpenRead("/tmp/chunk.bin")) ws.SendAsync(fs, 512, sent => Console.WriteLine("Stream sent: " + sent)); Console.ReadKey(true); } ``` ``` -------------------------------- ### Configure WebSocket Logging Level and Output Source: https://context7.com/sta/websocket-sharp/llms.txt Adjust the `Log.Level` property to control the verbosity of WebSocket logs, from `Trace` (most verbose) to `Fatal` (least verbose). Customize log output using the `Log.Output` delegate to redirect logs, for example, to a file. ```csharp using System; using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/echo")) { // Set log level (Trace < Debug < Info < Warn < Error < Fatal) ws.Log.Level = LogLevel.Debug; // Custom output action — e.g., write to a file ws.Log.Output = (logData, path) => { Console.ForegroundColor = logData.Level >= LogLevel.Warn ? ConsoleColor.Red : ConsoleColor.Gray; Console.WriteLine($"[{logData.Level}] {logData.Date:HH:mm:ss} {logData.Message}"); Console.ResetColor(); }; ws.OnMessage += (s, e) => Console.WriteLine(e.Data); ws.Connect(); // Write application-level log entries ws.Log.Info("Connection is up."); ws.Log.Debug("Sending test frame."); ws.Send("debug test"); Console.ReadKey(true); } ``` -------------------------------- ### Output WebSocket Debug Log Message Source: https://github.com/sta/websocket-sharp/blob/master/README.md Use the logging methods provided by the WebSocket class to output log messages at a specific level. This example shows how to output a debug message. ```csharp ws.Log.Debug ("This is a debug message."); ``` -------------------------------- ### WebSocket Client Initialization and Connection Source: https://github.com/sta/websocket-sharp/blob/master/README.md Demonstrates how to create a WebSocket client instance, connect to a server, send messages, and handle incoming messages. ```APIDOC ## WebSocket Client ## ### Description This section details how to use the `WebSocket` class to establish a connection to a WebSocket server, send data, and receive messages. ### Usage 1. **Include Namespace:** ```csharp using WebSocketSharp; ``` 2. **Create WebSocket Instance:** Instantiate the `WebSocket` class with the server URL. It's recommended to use a `using` statement for proper disposal. ```csharp using (var ws = new WebSocket ("ws://example.com")) { // ... connection logic ... } ``` Using a `using` block ensures the connection is closed with status code `1001` (going away) when the block is exited. 3. **Set Event Handlers:** - **`OnOpen`**: Fired when the connection is successfully established. ```csharp ws.OnOpen += (sender, e) => { // Connection opened logic }; ``` - **`OnMessage`**: Fired when a message is received from the server. ```csharp ws.OnMessage += (sender, e) => { if (e.IsText) { Console.WriteLine ("Received text: " + e.Data); } else if (e.IsBinary) { Console.WriteLine ("Received binary data."); } }; ``` Access received data via `e.Data` (string) for text messages or `e.RawData` (byte[]) for binary messages. - **`OnError`**: Fired when an error occurs during the WebSocket communication. ```csharp ws.OnError += (sender, e) => { Console.WriteLine ("Error: " + e.Message); if (e.Exception != null) { Console.WriteLine ("Exception: " + e.Exception.ToString()); } }; ``` Error details are available in `e.Message` and `e.Exception`. 4. **Connect and Send:** Call `ws.Connect()` to initiate the connection and `ws.Send()` to send data. ```csharp ws.Connect (); ws.Send ("Hello, server!"); ``` ### Example ```csharp using System; using WebSocketSharp; public class WebSocketClientExample { 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.OnOpen += (sender, e) => { Console.WriteLine ("Connection opened."); ws.Send ("Hello from client!"); }; ws.OnError += (sender, e) => Console.WriteLine ("Error: " + e.Message); ws.Connect (); Console.WriteLine ("Press any key to exit..."); Console.ReadKey (true); } } } ``` ``` -------------------------------- ### WebSocket Client Constructor and Connection Source: https://context7.com/sta/websocket-sharp/llms.txt Demonstrates how to create a WebSocket client instance, wire up event handlers for connection events, and establish a connection to a WebSocket server. ```APIDOC ## WebSocket Client — Constructor and Connection `new WebSocket(url, protocols[])` creates a client-side WebSocket instance targeting the given `ws://` or `wss://` URL. Calling `Connect()` performs the RFC 6455 handshake; `ConnectAsync()` does the same without blocking. ```csharp using System; using WebSocketSharp; // Create client (wss:// for secure; optional subprotocols) using (var ws = new WebSocket("ws://example.com:4649/chat", "chat-v1")) { // --- Events wired before Connect() --- ws.OnOpen += (sender, e) => Console.WriteLine("Connection established."); ws.OnMessage += (sender, e) => { if (e.IsText) Console.WriteLine("Text: " + e.Data); else if (e.IsBinary) Console.WriteLine("Binary: " + e.RawData.Length + " bytes"); else if (e.IsPing) Console.WriteLine("Ping received."); }; ws.OnError += (sender, e) => Console.WriteLine("Error: " + e.Message + (e.Exception != null ? " | " + e.Exception : "")); ws.OnClose += (sender, e) => Console.WriteLine($"Closed — code: {e.Code}, reason: {e.Reason}, clean: {e.WasClean}"); // Optional: emit OnMessage even for pings ws.EmitOnPing = true; ws.Connect(); Console.WriteLine("State: " + ws.ReadyState); // WebSocketState.Open Console.WriteLine("Protocol: " + ws.Protocol); // negotiated subprotocol Console.WriteLine("Alive: " + ws.IsAlive); // sends ping, waits for pong Console.ReadKey(true); } // Dispose closes with status 1001 (going away) ``` ``` -------------------------------- ### WebSocketServer Instance Creation and Service Addition Source: https://github.com/sta/websocket-sharp/blob/master/README.md Demonstrates how to create a WebSocketServer instance and add different WebSocket services with optional configurations. ```APIDOC ## WebSocketServer Instance Creation and Service Addition ### Description This section shows how to create a new instance of the `WebSocketServer` class and add WebSocket services to it. You can specify a port number and add services with specific behaviors and paths. An optional action can be provided to configure the behavior of the service. ### Method `WebSocketServer.AddWebSocketService(string path)` `WebSocketServer.AddWebSocketService(string path, Action initializer)` ### Parameters #### Path Parameters - **path** (string) - Required - The absolute path to the service. #### Request Body - **TBehavior** - Required - The type of the WebSocket behavior, which must inherit from `WebSocketBehavior` and have a public parameterless constructor. - **initializer** (Action) - Optional - An action to configure the behavior instance. ### Request Example ```csharp var wssv = new WebSocketServer (4649); wssv.AddWebSocketService ("/Echo"); wssv.AddWebSocketService ("/Chat"); wssv.AddWebSocketService ("/ChatWithNyan", s => s.Suffix = " Nyan!"); ``` ### Notes - If a `WebSocketServer` is created without a port number, it defaults to port 80 and requires root permissions to run. - The `WebSocketBehavior.IgnoreExtensions` property can be set to `true` to ignore extensions requested by the client. ``` -------------------------------- ### Get User Headers from WebSocket Handshake Response Source: https://github.com/sta/websocket-sharp/blob/master/README.md Access this property after the handshake is complete to retrieve user-defined headers sent by the server. ```csharp var id = ws.HandshakeResponseHeaders["ID"]; ``` -------------------------------- ### HttpServer Instance Creation and Service Addition Source: https://github.com/sta/websocket-sharp/blob/master/README.md Demonstrates how to create an HttpServer instance and add WebSocket services to it, similar to WebSocketServer. ```APIDOC ## HttpServer Instance Creation and Service Addition ### Description This section shows how to create an `HttpServer` instance, which is built upon `System.Net.HttpListener`, and add WebSocket services to it. The methods for adding services are analogous to those for `WebSocketServer`. ### Method `HttpServer.AddWebSocketService(string path)` `HttpServer.AddWebSocketService(string path, Action initializer)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the service. #### Request Body - **TBehavior** - Required - The type of the WebSocket behavior. - **initializer** (Action) - Optional - An action to configure the behavior instance. ### Request Example ```csharp var httpsv = new HttpServer (4649); httpsv.AddWebSocketService ("/Echo"); httpsv.AddWebSocketService ("/Chat"); httpsv.AddWebSocketService ("/ChatWithNyan", s => s.Suffix = " Nyan!"); ``` ``` -------------------------------- ### Create WebSocket Client and Connect Source: https://context7.com/sta/websocket-sharp/llms.txt Establishes a WebSocket client connection to a specified URL. Wire up event handlers for connection lifecycle events before calling Connect(). ```csharp using System; using WebSocketSharp; // Create client (wss:// for secure; optional subprotocols) using (var ws = new WebSocket("ws://example.com:4649/chat", "chat-v1")) { // --- Events wired before Connect() --- ws.OnOpen += (sender, e) => Console.WriteLine("Connection established."); ws.OnMessage += (sender, e) => { if (e.IsText) Console.WriteLine("Text: " + e.Data); else if (e.IsBinary) Console.WriteLine("Binary: " + e.RawData.Length + " bytes"); else if (e.IsPing) Console.WriteLine("Ping received."); }; ws.OnError += (sender, e) => Console.WriteLine("Error: " + e.Message + (e.Exception != null ? " | " + e.Exception : "")); ws.OnClose += (sender, e) => Console.WriteLine($"Closed — code: {e.Code}, reason: {e.Reason}, clean: {e.WasClean}"); // Optional: emit OnMessage even for pings ws.EmitOnPing = true; ws.Connect(); Console.WriteLine("State: " + ws.ReadyState); // WebSocketState.Open Console.WriteLine("Protocol: " + ws.Protocol); // negotiated subprotocol Console.WriteLine("Alive: " + ws.IsAlive); // sends ping, waits for pong Console.ReadKey(true); } // Dispose closes with status 1001 (going away) ``` -------------------------------- ### Create WebSocketServer Instance Source: https://github.com/sta/websocket-sharp/blob/master/README.md Instantiate a WebSocketServer with a specific port and add WebSocket services. Ensure the behavior class inherits from WebSocketBehavior and has a public parameterless constructor. ```csharp var wssv = new WebSocketServer (4649); wssv.AddWebSocketService ("/Echo"); wssv.AddWebSocketService ("/Chat"); wssv.AddWebSocketService ("/ChatWithNyan", s => s.Suffix = " Nyan!"); ``` -------------------------------- ### HTTP + WebSocket Hybrid Server with File Serving Source: https://context7.com/sta/websocket-sharp/llms.txt Sets up an HttpServer that handles both plain HTTP requests (serving files and handling GET/POST) and WebSocket upgrade requests. Requires registering WebSocket services. ```csharp using System; using System.IO; using System.Text; using WebSocketSharp; using WebSocketSharp.Server; using WebSocketSharp.Net; class EchoService : WebSocketBehavior { protected override void OnMessage (MessageEventArgs e) => Send(e.Data); } class Program { static void Main() { var httpsv = new HttpServer(4649); // Serve files from a document root httpsv.DocumentRootPath = "./Public"; // Register WebSocket services at specific paths httpsv.AddWebSocketService("/echo"); // Handle plain HTTP GET requests httpsv.OnGet += (sender, e) => { var req = e.Request; var res = e.Response; var path = req.RawUrl; Console.WriteLine("HTTP GET " + path); if (path == "/" || path == "/index.html") { var html = File.ReadAllBytes(httpsv.DocumentRootPath + "/index.html"); res.ContentType = "text/html"; res.ContentEncoding = Encoding.UTF8; res.ContentLength64 = html.Length; res.OutputStream.Write(html, 0, html.Length); } else { res.StatusCode = 404; } }; httpsv.OnPost += (sender, e) => { var body = new StreamReader(e.Request.InputStream).ReadToEnd(); Console.WriteLine("POST body: " + body); e.Response.StatusCode = 200; }; httpsv.Start(); Console.WriteLine($"HTTP+WS server on http://localhost:{httpsv.Port}"); Console.ReadKey(true); httpsv.Stop(); } } ``` -------------------------------- ### Connect to WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Initiate a connection to a WebSocket server using the Connect method. For asynchronous connections, use ConnectAsync. ```csharp ws.Connect (); ``` -------------------------------- ### Create WebSocket Instance Source: https://github.com/sta/websocket-sharp/blob/master/README.md Instantiate the WebSocket class with the server URL. Using a 'using' statement ensures the connection is closed properly. ```csharp var ws = new WebSocket ("ws://example.com"); ``` ```csharp using (var ws = new WebSocket ("ws://example.com")) { ... } ``` -------------------------------- ### WebSocket Client with Query String Source: https://github.com/sta/websocket-sharp/blob/master/README.md Create a WebSocket client instance with a URL that includes query string parameters for the handshake request. ```csharp var ws = new WebSocket ("ws://example.com/?name=nobita"); ``` -------------------------------- ### Create WebSocket Client with WSS Scheme Source: https://github.com/sta/websocket-sharp/blob/master/README.md Create a WebSocket client instance using a secure 'wss' URL. This initiates a secure connection using SSL/TLS. ```csharp var ws = new WebSocket ("wss://example.com"); ``` -------------------------------- ### Create HttpServer Instance Source: https://github.com/sta/websocket-sharp/blob/master/README.md Instantiate an HttpServer with a specific port and add WebSocket services. This class is used for handling HTTP requests that include WebSocket handshake requests. ```csharp var httpsv = new HttpServer (4649); httpsv.AddWebSocketService ("/Echo"); httpsv.AddWebSocketService ("/Chat"); httpsv.AddWebSocketService ("/ChatWithNyan", s => s.Suffix = " Nyan!"); ``` -------------------------------- ### Implement Echo WebSocket Service Source: https://github.com/sta/websocket-sharp/blob/master/README.md Create a custom WebSocket service by inheriting from WebSocketBehavior and overriding the OnMessage method to echo received data back to the client. ```csharp using System; using WebSocketSharp; using WebSocketSharp.Server; public class Echo : WebSocketBehavior { protected override void OnMessage (MessageEventArgs e) { Send (e.Data); } } ``` -------------------------------- ### Import WebSocketSharp Namespace Source: https://github.com/sta/websocket-sharp/blob/master/README.md Include this namespace to use the WebSocket class in your project. ```csharp using WebSocketSharp; ``` -------------------------------- ### WebSocket Client Compression Configuration Source: https://github.com/sta/websocket-sharp/blob/master/README.md Explains how to enable and configure the Per-message Compression extension for WebSocket clients. ```APIDOC ## WebSocket Client Compression Configuration ### Description This section details how a WebSocket client can enable the Per-message Compression extension. This involves setting the `Compression` property before connecting. ### Method `WebSocket.Compression` property setter ### Parameters #### Request Body - **Compression** (CompressionMethod) - Required - Set to `CompressionMethod.Deflate` to enable per-message compression. ### Request Example ```csharp ws.Compression = CompressionMethod.Deflate; ``` ### Notes - The client will send the `Sec-WebSocket-Extensions` header with `permessage-deflate` parameters. - The server must also support this extension for it to be successfully negotiated. ``` -------------------------------- ### Secure WebSocket Connection with SSL/TLS Source: https://context7.com/sta/websocket-sharp/llms.txt Demonstrates establishing a secure WebSocket connection using `wss://` URLs. Configures server certificate validation, enables specific TLS versions, and attaches client certificates for mutual TLS. ```csharp using System; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using WebSocketSharp; using (var ws = new WebSocket("wss://secure.example.com/data")) { // Custom server certificate validation ws.SslConfiguration.ServerCertificateValidationCallback = (sender, cert, chain, errors) => { if (errors == SslPolicyErrors.None) return true; Console.WriteLine("SSL errors: " + errors); return false; // reject on any error }; // Enable specific TLS versions ws.SslConfiguration.EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13; // Attach a client certificate if the server requires mutual TLS ws.SslConfiguration.ClientCertificates = new X509CertificateCollection { new X509Certificate2("/path/to/client.pfx", "pfx-password") }; ws.OnMessage += (s, e) => Console.WriteLine("Secure msg: " + e.Data); ws.Connect(); ws.Send("hello over TLS"); Console.ReadKey(true); } ``` -------------------------------- ### WebSocket Session Management and Broadcasting Source: https://context7.com/sta/websocket-sharp/llms.txt Demonstrates how to manage WebSocket sessions and broadcast messages to all connected clients using WebSocketSessionManager. Requires a WebSocketBehavior implementation. ```csharp using System; using WebSocketSharp; using WebSocketSharp.Server; public class NotifyService : WebSocketBehavior { protected override void OnOpen() { // Total session count Console.WriteLine("Total connected: " + Sessions.Count); // IDs of all sessions foreach (var id in Sessions.IDs) Console.WriteLine("Session: " + id); // Active sessions (those that responded to an internal ping) foreach (var id in Sessions.ActiveIDs) Console.WriteLine("Active: " + id); // Broadcast text to every client in this service Sessions.Broadcast("Server is live."); // Broadcast binary Sessions.Broadcast(new byte[] { 0xFF, 0x00 }); // Send to a specific session by ID Sessions.SendTo("hello unicast", ID); // Ping a specific session bool pongReceived = Sessions.PingTo(ID); Console.WriteLine("Pinged " + ID + ": " + pongReceived); // Close a specific session // Sessions.CloseSession(ID, CloseStatusCode.Normal, "server closing"); } protected override void OnMessage (MessageEventArgs e) => Sessions.Broadcast(e.Data); // relay to all } ``` -------------------------------- ### HTTP Authentication (Server) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure HTTP authentication schemes, realms, and user credential finders for a WebSocket server. ```APIDOC ## HTTP Authentication (Server) ### Description Configure HTTP authentication schemes, realms, and user credential finders for a WebSocket server. ### Method `WebSocketServer.Start()` and related properties. ### Parameters - **AuthenticationSchemes** (AuthenticationSchemes) - Set the authentication scheme (e.g., `AuthenticationSchemes.Basic`, `AuthenticationSchemes.Digest`). - **Realm** (string) - The authentication realm. - **UserCredentialsFinder** (Func) - A function to find user credentials based on identity. ### Request Example (Basic Authentication) ```csharp wssv.AuthenticationSchemes = AuthenticationSchemes.Basic; wssv.Realm = "WebSocket Test"; wssv.UserCredentialsFinder = id => { var name = id.Name; return name == "nobita" ? new NetworkCredential (name, "password", "gunfighter") : null; }; ``` ### Request Example (Digest Authentication) ```csharp wssv.AuthenticationSchemes = AuthenticationSchemes.Digest; ``` ``` -------------------------------- ### Enable WebSocket Compression with Deflate Source: https://context7.com/sta/websocket-sharp/llms.txt Set the `Compression` property to `CompressionMethod.Deflate` before connecting to advertise the `permessage-deflate` extension. The server negotiates the extension, enabling transparent compression and decompression of messages. ```csharp using System; using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/compress")) { // Must be set before Connect() ws.Compression = CompressionMethod.Deflate; ws.OnOpen += (s, e) => Console.WriteLine("Extensions negotiated: " + ws.Extensions); // e.g. "permessage-deflate; server_no_context_takeover; client_no_context_takeover" ws.OnMessage += (s, e) => Console.WriteLine("Decompressed: " + e.Data); ws.Connect(); ws.Send("This payload will be deflate-compressed on the wire."); Console.ReadKey(true); } ``` -------------------------------- ### Implement Chat WebSocket Service Source: https://github.com/sta/websocket-sharp/blob/master/README.md Develop a chat service by extending WebSocketBehavior. Override OnMessage to broadcast received messages to all connected clients, optionally appending a suffix. ```csharp using System; using WebSocketSharp; using WebSocketSharp.Server; public class Chat : WebSocketBehavior { private string _suffix; public Chat () { _suffix = String.Empty; } public string Suffix { get { return _suffix; } set { _suffix = value ?? String.Empty; } } protected override void OnMessage (MessageEventArgs e) { Sessions.Broadcast (e.Data + _suffix); } } ``` -------------------------------- ### Check WebSocket Liveness with Ping Source: https://context7.com/sta/websocket-sharp/llms.txt Shows how to check if a WebSocket connection is alive using `Ping()` and `Ping(string)`. The `IsAlive` property is a convenience wrapper. Adjusts the wait timeout for Pong replies. ```csharp using System; using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/service")) { ws.Connect(); bool alive = ws.Ping(); Console.WriteLine("Alive (empty ping): " + alive); bool aliveWithMsg = ws.Ping("are you there?"); Console.WriteLine("Alive (payload ping): " + aliveWithMsg); // IsAlive property is a convenience wrapper for Ping() Console.WriteLine("IsAlive: " + ws.IsAlive); // Adjust the wait timeout ws.WaitTime = TimeSpan.FromSeconds(2); } ``` -------------------------------- ### WebSocket Client - Connect Source: https://github.com/sta/websocket-sharp/blob/master/README.md Connects to the WebSocket server. An asynchronous version is also available. ```APIDOC ## WebSocket.Connect ### Description Connects to the WebSocket server. Use `ConnectAsync()` for asynchronous connection. ### Method ```csharp ws.Connect (); ``` ``` -------------------------------- ### Connect Through HTTP Proxy Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure a WebSocket client to connect through an HTTP proxy server, optionally providing authentication credentials. Ensure the proxy server (e.g., Squid) is configured to allow CONNECT requests. ```csharp var ws = new WebSocket ("ws://example.com"); ws.SetProxy ("http://localhost:3128", "nobita", "password"); ``` -------------------------------- ### Configure Secure WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure a WebSocket server for secure connections by providing a port number and setting the SSL certificate. The certificate should be a valid X509Certificate2 object. ```csharp var wssv = new WebSocketServer (5963, true); wssv.SslConfiguration.ServerCertificate = new X509Certificate2 ( "/path/to/cert.pfx", "password for cert.pfx" ); ``` -------------------------------- ### HTTP Authentication (Client) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure HTTP Basic or Digest authentication for a WebSocket client by setting credentials before connecting. ```APIDOC ## HTTP Authentication (Client) ### Description Configure HTTP Basic or Digest authentication for a WebSocket client by setting credentials before connecting. ### Method `WebSocket.SetCredentials(string, string, bool)` ### Parameters - **userName** (string) - The username for authentication. - **password** (string) - The password for authentication. - **preAuth** (bool) - If true, sends credentials for Basic authentication in the first handshake. Otherwise, sends in the second handshake based on the server's response. ### Request Example ```csharp ws.SetCredentials ("nobita", "password", preAuth); ``` ``` -------------------------------- ### WebSocket Authentication with Basic/Digest Source: https://context7.com/sta/websocket-sharp/llms.txt Configures HTTP Basic or Digest credentials for WebSocket authentication using `SetCredentials()`. Supports proactive credential sending (`preAuth: true`) or challenge-response (`preAuth: false`). ```csharp using System; using WebSocketSharp; using (var ws = new WebSocket("ws://api.example.com/feed")) { // preAuth=true → Basic header sent immediately in first request // preAuth=false → wait for 401, then respond (Basic or Digest) ws.SetCredentials("alice", "s3cr3t", preAuth: false); ws.OnMessage += (s, e) => Console.WriteLine(e.Data); ws.Connect(); // performs challenge-response automatically if needed ws.Send("subscribe"); Console.ReadKey(true); } ``` -------------------------------- ### Handle WebSocket OnOpen Event Source: https://github.com/sta/websocket-sharp/blob/master/README.md This event handler is triggered when the WebSocket connection is successfully established. ```csharp ws.OnOpen += (sender, e) => { ... }; ``` -------------------------------- ### WebSocket Server Namespace Source: https://github.com/sta/websocket-sharp/blob/master/README.md Import the WebSocketSharp.Server namespace to use WebSocketBehavior and WebSocketServer classes for server-side implementations. ```csharp using WebSocketSharp.Server; ``` -------------------------------- ### WebSocket Server Extension Handling Source: https://github.com/sta/websocket-sharp/blob/master/README.md Describes how WebSocket servers can choose to ignore Per-message Compression extensions requested by clients. ```APIDOC ## WebSocket Server Extension Handling ### Description This section explains how a WebSocket server can be configured to ignore any WebSocket extensions requested by a client, specifically the Per-message Compression extension. ### Method `WebSocketBehavior.IgnoreExtensions` property setter ### Parameters #### Request Body - **IgnoreExtensions** (bool) - Required - Set to `true` to ignore client-requested extensions. ### Request Example ```csharp // Within the WebSocketBehavior constructor or initializer serviceInstance.IgnoreExtensions = true; // Or when adding the service wssv.AddWebSocketService ( "/Chat", s => s.IgnoreExtensions = true // To ignore the extensions requested from a client. ); ``` ### Notes - If set to `true`, the server will not include the `Sec-WebSocket-Extensions` header in its handshake response. ``` -------------------------------- ### Enable Per-message Compression Client Source: https://github.com/sta/websocket-sharp/blob/master/README.md Enable the Per-message Compression extension for a WebSocket client by setting the Compression property before connecting. This allows for compressed data transfer. ```csharp ws.Compression = CompressionMethod.Deflate; ``` -------------------------------- ### WebSocket.Send — Sending Data Synchronously Source: https://context7.com/sta/websocket-sharp/llms.txt Explains how to send text or binary data over an open WebSocket connection using synchronous methods. Covers sending strings, byte arrays, files, and streams. ```APIDOC ## WebSocket.Send — Sending Data Synchronously `Send(string)`, `Send(byte[])`, `Send(FileInfo)`, and `Send(Stream, int)` transmit text or binary data over an open connection. All overloads are synchronous and throw `InvalidOperationException` if the state is not `Open`. ```csharp using System; using System.IO; using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/echo")) { ws.OnMessage += (s, e) => Console.WriteLine("Echo: " + e.Data); ws.Connect(); // Send a text frame ws.Send("Hello, Server!"); // Send binary data ws.Send(new byte[] { 0x01, 0x02, 0x03 }); // Send a file as binary data ws.Send(new FileInfo("/tmp/data.bin")); // Send N bytes from a stream using (var ms = new MemoryStream(new byte[] { 0xDE, 0xAD, 0xBE, 0xEF })) ws.Send(ms, 4); Console.ReadKey(true); } ``` ``` -------------------------------- ### WebSocket Secure Connection (Client) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Details how to establish a secure WebSocket connection from the client-side using WSS scheme and custom certificate validation. ```APIDOC ## WebSocket Secure Connection (Client) ### Description This section covers how to create a secure WebSocket connection as a client using the `wss` scheme. It also explains how to provide a custom callback for validating the server's SSL/TLS certificate. ### Method `new WebSocket(string url)` constructor `WebSocket.SslConfiguration.ServerCertificateValidationCallback` property setter ### Parameters #### Request Body - **url** (string) - Required - The WebSocket URL, starting with `wss://` for secure connections. - **ServerCertificateValidationCallback** (Func) - Optional - A callback function to validate the server certificate. It receives the sender, certificate, chain, and SSL policy errors, and should return `true` if the certificate is considered valid. ### Request Example ```csharp var ws = new WebSocket ("wss://example.com"); ws.SslConfiguration.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { // Custom validation logic here... return true; // Return true if the certificate is valid }; ``` ### Notes - The default `ServerCertificateValidationCallback` always returns `true`. ``` -------------------------------- ### Close WebSocket Connection Source: https://context7.com/sta/websocket-sharp/llms.txt Demonstrates closing a WebSocket connection using `Close()` and `CloseAsync()`. Supports normal closure, closure with status codes, and closure with a reason string. The async variant returns immediately. ```csharp using WebSocketSharp; using (var ws = new WebSocket("ws://localhost:4649/service")) { ws.OnClose += (s, e) => Console.WriteLine($"Closed: {e.Code} ({e.Reason}) clean={e.WasClean}"); ws.Connect(); ws.Send("goodbye"); // Normal close (no code) // ws.Close(); // Close with standard code ws.Close(CloseStatusCode.Normal); // Close with code + reason // ws.Close(CloseStatusCode.Away, "navigating away"); // Async close — does not block // ws.CloseAsync(1000, "done"); } ``` -------------------------------- ### WebSocket Server - WebSocketBehavior Source: https://github.com/sta/websocket-sharp/blob/master/README.md Defines the behavior of a WebSocket service by inheriting from WebSocketBehavior. ```APIDOC ## WebSocketBehavior ### Description Create a class that inherits from `WebSocketBehavior` to define custom WebSocket service logic. Override methods like `OnMessage`, `OnOpen`, `OnError`, and `OnClose` to handle specific events. ### Echo Service Example ```csharp using System; using WebSocketSharp; using WebSocketSharp.Server; public class Echo : WebSocketBehavior { protected override void OnMessage (MessageEventArgs e) { Send (e.Data); } } ``` ### Chat Service Example ```csharp using System; using WebSocketSharp; using WebSocketSharp.Server; public class Chat : WebSocketBehavior { private string _suffix; public Chat () { _suffix = String.Empty; } public string Suffix { get { return _suffix; } set { _suffix = value ?? String.Empty; } } protected override void OnMessage (MessageEventArgs e) { Sessions.Broadcast (e.Data + _suffix); } } ``` ### Key Properties and Methods - **OnMessage (MessageEventArgs e)**: Called when a message is received. - **OnOpen ()**: Called when a connection is opened. - **OnError (ErrorEventArgs e)**: Called when an error occurs. - **OnClose (CloseEventArgs e)**: Called when a connection is closed. - **Send (string data)**: Sends data to the client on the current session. - **Sessions**: Property returning `WebSocketSessionManager` to access all sessions in the service. - **Sessions.Broadcast (string data)**: Sends data to all clients in the service. ``` -------------------------------- ### Configure WebSocket Cookies and Custom Headers Source: https://context7.com/sta/websocket-sharp/llms.txt Use `SetCookie` to attach cookies and `SetUserHeader` to add custom headers to the handshake request. Access server response metadata via `HandshakeResponseHeaders` and `HandshakeResponseCookies` after the connection is open. ```csharp using System; using WebSocketSharp; using WebSocketSharp.Net; using (var ws = new WebSocket("ws://example.com/session")) { // Client-side cookie ws.SetCookie(new Cookie("session_id", "abc123")); // Custom request header ws.SetUserHeader("X-Client-Version", "2.0"); ws.SetUserHeader("X-Request-ID", Guid.NewGuid().ToString()); // Set the Origin header ws.Origin = "http://example.com"; ws.OnOpen += (s, e) => { var responseHeaders = ws.HandshakeResponseHeaders; if (responseHeaders != null) Console.WriteLine("Server responded with: " + responseHeaders["X-Server-Token"]); var responseCookies = ws.HandshakeResponseCookies; if (responseCookies != null) foreach (Cookie c in responseCookies) Console.WriteLine($"Response cookie: {c.Name}={c.Value}"); }; ws.Connect(); Console.ReadKey(true); } ``` -------------------------------- ### Implement Origin and Cookie Validation in WebSocketBehavior Source: https://context7.com/sta/websocket-sharp/llms.txt Configure WebSocket services to validate the Origin header and customize cookie handling during the handshake. Reject connections from unexpected origins and manage session or tracking cookies. ```csharp using System; using WebSocketSharp; using WebSocketSharp.Net; using WebSocketSharp.Server; class ValidatedChat : WebSocketBehavior { protected override void OnMessage (MessageEventArgs e) => Sessions.Broadcast (e.Data); } class Program { static void Main () { var wssv = new WebSocketServer (4649); wssv.AddWebSocketService ( "/chat", s => { // Reject connections from unexpected origins s.OriginValidator = originHeader => { if (string.IsNullOrEmpty (originHeader)) return false; Uri origin; return Uri.TryCreate (originHeader, UriKind.Absolute, out origin) && (origin.Host == "example.com" || origin.Host == "localhost"); }; // Inspect request cookies; set or expire response cookies s.CookiesResponder = (reqCookies, resCookies) => { foreach (Cookie c in reqCookies) { Console.WriteLine ($"Cookie received: {c.Name}={c.Value}"); if (c.Name == "session") { // extend the cookie lifetime c.Expires = DateTime.UtcNow.AddHours (1); resCookies.Add (c); } } // Issue a new tracking cookie resCookies.Add (new Cookie ("ws_connected", "1") { Expires = DateTime.UtcNow.AddMinutes (30) }); }; }); wssv.Start (); Console.ReadKey (true); wssv.Stop (); } } ``` -------------------------------- ### Configure Squid Proxy for WebSocket Connections Source: https://github.com/sta/websocket-sharp/blob/master/README.md To enable WebSocket connections through Squid, you may need to disable the 'http_access deny CONNECT !SSL_ports' rule in squid.conf. ```text # Deny CONNECT to other than SSL ports #http_access deny CONNECT !SSL_ports ``` -------------------------------- ### Enable Digest Authentication for WebSocket Server Source: https://github.com/sta/websocket-sharp/blob/master/README.md Configure the WebSocket server to use Digest authentication by setting the `AuthenticationSchemes` property. ```csharp wssv.AuthenticationSchemes = AuthenticationSchemes.Digest; ``` -------------------------------- ### Query String (Client) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Send query string parameters in the handshake request by including them in the WebSocket URL. ```APIDOC ## Query String (Client) ### Description Send query string parameters in the handshake request by including them in the WebSocket URL. ### Method `new WebSocket(string url)` ### Parameters - **url** (string) - The WebSocket URL including query string parameters. ### Request Example ```csharp var ws = new WebSocket ("ws://example.com/?name=nobita"); ``` ``` -------------------------------- ### Cookies (Server) Source: https://github.com/sta/websocket-sharp/blob/master/README.md Respond to cookies in handshake requests by setting a `CookiesResponder` in `WebSocketBehavior`. ```APIDOC ## Cookies (Server) ### Description Respond to cookies in handshake requests by setting a `CookiesResponder` in `WebSocketBehavior`. ### Method `WebSocketServer.AddWebSocketService(string, Action)` with `CookiesResponder`. ### Usage Example ```csharp wssv.AddWebSocketService ( "/Chat", s => { s.CookiesResponder = (reqCookies, resCookies) => { foreach (var cookie in reqCookies) { cookie.Expired = true; resCookies.Add (cookie); } }; } ); ``` ```