Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

Logo

Welcome to websocket-sharp!

websocket-sharp supports:

Build

websocket-sharp is built as a single assembly, websocket-sharp.dll.

websocket-sharp is developed with MonoDevelop. So the simple way to build is to open websocket-sharp.sln and run build for websocket-sharp project with any of the build configurations (e.g. Debug) in MonoDevelop.

Install

Self Build

You should add your websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) to the library references of your project.

NuGet Gallery

websocket-sharp is available on the NuGet Gallery.

You can add websocket-sharp to your project using the NuGet Package Manager, the following command in the Package Manager Console.

PM> Install-Package WebSocketSharp.clone

Usage

WebSocket Client

usingSystem;usingWebSocketSharp;namespaceExample{publicclassProgram{publicstaticvoidMain(string[]args){using(varws=newWebSocket("ws://dragonsnest.far/Laputa")){ws.OnMessage= e =>{Console.WriteLine("Laputa says: "+e.Data);}
ws.Connect();ws.Send("BALUS");Console.ReadKey(true);}}}}

Step 1

Required namespace.

usingWebSocketSharp;

The WebSocket class exists in the WebSocketSharp namespace.

Step 2

Creating a new instance of the WebSocket class with the WebSocket URL to connect.

using(varws=newWebSocket("ws://example.com")){
...}

The WebSocket class inherits the System.IDisposable interface, so you can use the using statement. And the WebSocket connection will be closed with close status 1001 (going away) when the control leaves the using block.

Step 3

Setting the WebSocket events.

WebSocket.OnOpen Event

A WebSocket.OnOpen event occurs when the WebSocket connection has been established.

ws.OnOpen=(sender,e)=>{
...};

e has passed as the System.EventArgs.Empty, so you don't use e.

WebSocket.OnMessage Event

A WebSocket.OnMessage event occurs when the WebSocket receives a message.

ws.OnMessage+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.MessageEventArgs.

e.Type property returns either WebSocketSharp.Opcode.Text or WebSocketSharp.Opcode.Binary that represents the type of the message. So by checking it, you can determine which item you should use.

If it returns Opcode.Text, you should use e.Data property that returns a string (represents the Text message).

Or if it returns Opcode.Binary, you should use e.RawData property that returns a byte[] (represents the Binary message).

if(e.Type==Opcode.Text){// Do something with e.Data.
...return;}if(e.Type==Opcode.Binary){// Do something with e.RawData.
...return;}
WebSocket.OnError Event

A WebSocket.OnError event occurs when the WebSocket gets an error.

ws.OnError+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.ErrorEventArgs.

e.Message property returns a string that represents the error message. So you should use it to get the error message.

And if the error is due to an exception, you can get the System.Exception instance that caused the error, by using e.Exception property.

WebSocket.OnClose Event

A WebSocket.OnClose event occurs when the WebSocket connection has been closed.

ws.OnClose+=(sender,e)=>{
...};

e has passed as a WebSocketSharp.CloseEventArgs.

e.Code property returns a ushort that represents the status code indicating the reason for the close, and e.Reason property returns a string that represents the reason for the close. So you should use them to get the reason for the close.

Step 4

Connecting to the WebSocket server.

ws.Connect();

If you would like to connect to the server asynchronously, you should use the WebSocket.ConnectAsync () method.

Step 5

Sending a data to the WebSocket server.

ws.Send(data);

The WebSocket.Send method is overloaded.

You can use the WebSocket.Send (string), WebSocket.Send (byte[]), or WebSocket.Send (System.IO.FileInfo) method to send a data.

If you would like to send a data asynchronously, you should use the WebSocket.SendAsync method.

ws.SendAsync(data,completed);

And also if you would like to do something when the send is complete, you should set completed to any Action<bool> delegate.

Step 6

Closing the WebSocket connection.

ws.Close(code,reason);

If you would like to close the connection explicitly, you should use the WebSocket.Close method.

The WebSocket.Close method is overloaded.

You can use the WebSocket.Close (), WebSocket.Close (ushort), WebSocket.Close (WebSocketSharp.CloseStatusCode), WebSocket.Close (ushort, string), or WebSocket.Close (WebSocketSharp.CloseStatusCode, string) method to close the connection.

If you would like to close the connection asynchronously, you should use the WebSocket.CloseAsync method.

WebSocket Server

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;namespaceExample{publicclassLaputa:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){varmsg=e.Data=="BALUS"?"I've been balused already...":"I'm not available now.";Send(msg);}}publicclassProgram{publicstaticvoidMain(string[]args){varwssv=newWebSocketServer("ws://dragonsnest.far");wssv.AddWebSocketService<Laputa>("/Laputa");wssv.Start();Console.ReadKey(true);wssv.Stop();}}}

Step 1

Required namespace.

usingWebSocketSharp.Server;

The WebSocketBehavior and WebSocketServer classes exist in the WebSocketSharp.Server namespace.

Step 2

Creating the class that inherits the WebSocketBehavior class.

For example, if you would like to provide an echo service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassEcho:WebSocketBehavior{protectedoverridevoidOnMessage(MessageEventArgse){Send(e.Data);}}

And if you would like to provide a chat service,

usingSystem;usingWebSocketSharp;usingWebSocketSharp.Server;publicclassChat:WebSocketBehavior{privatestring_suffix;publicChat():this(null){}publicChat(stringsuffix){_suffix=suffix??String.Empty;}protectedoverridevoidOnMessage(MessageEventArgse){Sessions.Broadcast(e.Data+_suffix);}}

You can define the behavior of any WebSocket service by creating the class that inherits the WebSocketBehavior class.

If you override the WebSocketBehavior.OnMessage (MessageEventArgs) method, it's called when the WebSocket used in the current session in the service receives a message.

And if you override the WebSocketBehavior.OnOpen (), WebSocketBehavior.OnError (ErrorEventArgs), and WebSocketBehavior.OnClose (CloseEventArgs) methods, each of them is called when each event of the WebSocket (the OnOpen, OnError, and OnClose events) occurs.

The WebSocketBehavior.Send method sends a data to the client on the current session in the service.

If you would like to access the sessions in the service, you should use the WebSocketBehavior.Sessions property (returns a WebSocketSharp.Server.WebSocketSessionManager).

The WebSocketBehavior.Sessions.Broadcast method broadcasts a data to every client in the service.

Step 3

Creating an instance of the WebSocketServer class.

varwssv=newWebSocketServer(4649);wssv.AddWebSocketService<Echo>("/Echo");wssv.AddWebSocketService<Chat>("/Chat");wssv.AddWebSocketService<Chat>("/ChatWithNyan",()=>newChat(" Nyan!"));

You can add any WebSocket service to your WebSocketServer with the specified behavior and path to the service, using the WebSocketServer.AddWebSocketService<TBehaviorWithNew> (string) or WebSocketServer.AddWebSocketService<TBehavior> (string, Func<TBehavior>) method.

The type of TBehaviorWithNew must inherit the WebSocketBehavior class, and must have a public parameterless constructor.

And also the type of TBehavior must inherit the WebSocketBehavior class.

So you can use the classes created in Step 2 to add the service.

If you create an instance of the WebSocketServer class without a port number, the WebSocketServer set the port number to 80 automatically. So it's necessary to run with root permission.

$ sudo mono example2.exe

Step 4

Starting the WebSocket server.

wssv.Start();

Step 5

Stopping the WebSocket server.

wssv.Stop(code,reason);

The WebSocketServer.Stop method is overloaded.

You can use the WebSocketServer.Stop (), WebSocketServer.Stop (ushort, string), or WebSocketServer.Stop (WebSocketSharp.CloseStatusCode, string) method to stop the server.

WebSocket Extensions

Per-message Compression

websocket-sharp supports the Per-message Compression extension. (But it doesn't support with the extension parameters.)

If you would like to enable this extension as a WebSocket client, you should set such as the following.

ws.Compression=CompressionMethod.Deflate;

And then your client sends the following header with the connection request to the server.

Sec-WebSocket-Extensions: permessage-deflate

If the server supports this extension, it returns the same header. And when your client receives that header, it enables this extension.

Secure Connection

websocket-sharp supports the Secure Connection with SSL/TLS.

As a WebSocket Client, you should create an instance of the WebSocket class with the wss scheme WebSocket URL.

using(varws=newWebSocket("wss://example.com")){
...}

And if you would like to use the custom validation for the server certificate, you should set the WebSocket.SslConfiguration.ServerCertificateValidationCallback property.

ws.SslConfiguration.ServerCertificateValidationCallback=(sender,certificate,chain,sslPolicyErrors)=>{// Do something to validate the server certificate.
...return true;// If the server certificate is valid.};

If you set this property to nothing, the validation does nothing with the server certificate, and returns true.

As a WebSocket Server, you should create an instance of the WebSocketServer or HttpServer class with some settings for secure connection, such as the following.

varwssv=newWebSocketServer(4649,true);wssv.SslConfiguration.ServerCertificate=newX509Certificate2("/path/to/cert.pfx","password for cert.pfx");

HTTP Authentication

websocket-sharp supports the HTTP Authentication (Basic/Digest).

As a WebSocket Client, you should set a pair of user name and password for the HTTP authentication, using the WebSocket.SetCredentials (string, string, bool) method before connecting.

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

If preAuth is true, the WebSocket sends the Basic authentication credentials with the first connection request to the server.

Or if preAuth is false, the WebSocket sends either the Basic or Digest (determined by the unauthorized response to the first connection request) authentication credentials with the second connection request to the server.

As a WebSocket Server, you should set an HTTP authentication scheme, a realm, and any function to find the user credentials before starting, such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Basic;wssv.Realm="WebSocket Test";wssv.UserCredentialsFinder= id =>{varname=id.Name;// Return user name, password, and roles.returnname=="nobita"?newNetworkCredential(name,"password","gunfighter"):null;// If the user credentials aren't found.};

If you would like to provide the Digest authentication, you should set such as the following.

wssv.AuthenticationSchemes=AuthenticationSchemes.Digest;

Query String, Origin header and Cookies

As a WebSocket Client, if you would like to send the Query String with the WebSocket connection request to the server, you should create an instance of the WebSocket class with the WebSocket URL that includes the Query string parameters.

using(varws=newWebSocket("ws://example.com/?name=nobita")){
...}

And if you would like to send the Origin header with the WebSocket connection request to the server, you should set the WebSocket.Origin property to an allowable value as the Origin header before connecting, such as the following.

ws.Origin="http://example.com";

And if you would like to send the Cookies with the WebSocket connection request to the server, you should set any cookie using the WebSocket.SetCookie (WebSocketSharp.Net.Cookie) method before connecting, such as the following.

ws.SetCookie(newCookie("name","nobita"));

As a WebSocket Server, if you would like to get the Query String included in each WebSocket connection request, you should access the WebSocketBehavior.Context.QueryString property, such as the following.

publicclassChat:WebSocketBehavior{privatestring_name;
...protectedoverridevoidOnOpen(){_name=Context.QueryString["name"];}
...}

And if you would like to validate the Origin header, Cookies, or both included in each WebSocket connection request, you should set each validation with your WebSocketBehavior, for example, using the AddWebSocketService<TBehavior> (string, Func<TBehavior>) method with initializing, such as the following.

wssv.AddWebSocketService<Chat>("/Chat",()=>newChat(){OriginValidator= val =>{// Check the value of the Origin header, and return true if valid.Uriorigin;return!val.IsNullOrEmpty()&&Uri.TryCreate(val,UriKind.Absolute,outorigin)&&origin.Host=="example.com";},CookiesValidator=(req,res)=>{// Check the Cookies in 'req', and set the Cookies to send to the client with 'res'// if necessary.foreach(Cookiecookieinreq){cookie.Expired=true;res.Add(cookie);}returntrue;// If valid.}});

Also, if you would like to get each value of the Origin header and cookies, you should access each of the WebSocketBehavior.Context.Origin and WebSocketBehavior.Context.CookieCollection properties.

Connecting through the HTTP Proxy server

websocket-sharp supports to connect through the HTTP Proxy server.

If you would like to connect to a WebSocket server through the HTTP Proxy server, you should set the proxy server URL, and if necessary, a pair of user name and password for the proxy server authentication (Basic/Digest), using the WebSocket.SetProxy (string, string, string) method before connecting.

varws=newWebSocket("ws://example.com");ws.SetProxy("http://localhost:3128","nobita","password");

I tested this with the Squid. And it's necessary to disable the following configuration option in squid.conf (e.g. /etc/squid/squid.conf).

# Deny CONNECT to other than SSL ports
#http_access deny CONNECT !SSL_ports

Supported WebSocket Specifications

websocket-sharp supports RFC 6455, and it's based on the following WebSocket references:

License

websocket-sharp is provided under The MIT License.

About

A C# implementation of the WebSocket protocol client and server

Resources

Stars

33 stars

Watchers

7 watching

Forks

Releases

Packages

Used by

Contributors

Languages