websocket-sharp is a C# implementation of the WebSocket protocol client and server.
- master: Main branch.
- hybi-00: A branch for older draft-ietf-hybi-thewebsocketprotocol-00. No longer maintained.
- draft75: A branch for even more old draft-hixie-thewebsocketprotocol-75. No longer maintained.
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 the websocket-sharp project with any of the build configurations (e.g. Debug) in the MonoDevelop.
You should add websocket-sharp.dll (e.g. /path/to/websocket-sharp/bin/Debug/websocket-sharp.dll) that you built it yourself to the library references of your project.
If you use websocket-sharp.dll in your Unity project, you should add it to any folder of your project (e.g. Assets/Plugins) in the Unity Editor.
websocket-sharp has now been displayed on the NuGet Gallery, as still a prerelease version.
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 -Pre
websocket-sharp has now been displayed on the Unity Asset Store.
That's priced at US$15. I think your $15 makes this project more better and accelerated, Thank you!
websocket-sharp supports .NET 3.5 (includes compatible) or later.
using System;
using WebSocketSharp;
namespace Example
{
public class Program
{
public static void Main (string [] args)
{
using (var ws = new WebSocket ("ws://dragonsnest.far/Laputa"))
{
ws.OnMessage += (sender, e) =>
{
Console.WriteLine ("Laputa says: " + e.Data);
};
ws.Connect ();
ws.Send ("BALUS");
Console.ReadKey (true);
}
}
}
}
Required namespace.
using WebSocketSharp;
The WebSocket
class exists in the WebSocketSharp
namespace.
Creating an instance of the WebSocket
class with the specified WebSocket URL to connect.
using (var ws = new WebSocket ("ws://example.com"))
{
...
}
The WebSocket
class inherits the IDisposable
interface, so you can use the using
statement.
Setting the WebSocket
events.
A WebSocket.OnOpen
event occurs when the WebSocket connection has been established.
ws.OnOpen += (sender, e) =>
{
...
};
e
has passed as EventArgs.Empty
, so you don't use e
.
A WebSocket.OnMessage
event occurs when the WebSocket
receives a WebSocket data frame.
ws.OnMessage += (sender, e) =>
{
...
};
e.Type
(WebSocketSharp.MessageEventArgs.Type
, its type is WebSocketSharp.Opcode
) indicates the type of a received data. So by checking it, you determine which item you should use.
If e.Type
equals Opcode.TEXT
, you use e.Data
(WebSocketSharp.MessageEventArgs.Data
, its type is string
) that contains a received Text data.
If e.Type
equals Opcode.BINARY
, you use e.RawData
(WebSocketSharp.MessageEventArgs.RawData
, its type is byte []
) that contains a received Binary data.
if (e.Type == Opcode.TEXT)
{
// Do something with e.Data
return;
}
if (e.Type == Opcode.BINARY)
{
// Do something with e.RawData
return;
}
A WebSocket.OnError
event occurs when the WebSocket
gets an error.
ws.OnError += (sender, e) =>
{
...
};
e.Message
(WebSocketSharp.ErrorEventArgs.Message
, its type is string
) contains an error message, so you use it.
A WebSocket.OnClose
event occurs when the WebSocket connection has been closed.
ws.OnClose += (sender, e) =>
{
...
};
e.Code
(WebSocketSharp.CloseEventArgs.Code
, its type is ushort
) contains a status code indicating the reason for closure and e.Reason
(WebSocketSharp.CloseEventArgs.Reason
, its type is string
) contains the reason for closure, so you use them.
Connecting to the WebSocket server.
ws.Connect ();
Sending a data.
ws.Send (data);
The WebSocket.Send
method is overloaded.
The types of data
are string
, byte []
and System.IO.FileInfo
.
In addition, the WebSocket.Send (stream, length)
method exists, too.
These methods don't wait for the send to be complete. This means that these methods behave asynchronously.
If you do something when the send is complete, you use any of some WebSocket.Send (data, completed)
methods.
Closing the WebSocket connection.
ws.Close (code, reason);
If you close the WebSocket connection explicitly, you use the WebSocket.Close
method.
The WebSocket.Close
method is overloaded.
The types of code
are WebSocketSharp.CloseStatusCode
and ushort
, and the type of reason
is string
.
In addition, the WebSocket.Close ()
and WebSocket.Close (code)
methods exist, too.
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace Example
{
public class Laputa : WebSocketService
{
protected override void OnMessage (MessageEventArgs e)
{
var msg = e.Data == "BALUS"
? "I've been balused already..."
: "I'm not available now.";
Send (msg);
}
}
public class Program
{
public static void Main (string [] args)
{
var wssv = new WebSocketServer ("ws://dragonsnest.far");
wssv.AddWebSocketService<Laputa> ("/Laputa");
wssv.Start ();
Console.ReadKey (true);
wssv.Stop ();
}
}
}
Required namespace.
using WebSocketSharp.Server;
The WebSocketService
and WebSocketServer
classes exist in the WebSocketSharp.Server
namespace.
Creating the class that inherits the WebSocketService
class.
For example, if you provide an echo service,
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Echo : WebSocketService
{
protected override void OnMessage (MessageEventArgs e)
{
Send (e.Data);
}
}
And if you provide a chat service,
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Chat : WebSocketService
{
private string _suffix;
public Chat ()
: this (String.Empty)
{
}
public Chat (string suffix)
{
_suffix = suffix;
}
protected override void OnMessage (MessageEventArgs e)
{
Sessions.Broadcast (e.Data + _suffix);
}
}
If you override the WebSocketService.OnMessage
method, it's bound to the server side WebSocket.OnMessage
event.
And if you override the WebSocketService.OnOpen
, WebSocketService.OnError
and WebSocketService.OnClose
methods, each of them is bound to each server side event of WebSocket.OnOpen
, WebSocket.OnError
and WebSocket.OnClose
.
The WebSocketService.Send
method sends a data to the client of the current session to the WebSocket service.
The WebSocketService.Sessions
(its type is WebSocketSharp.Server.WebSocketSessionManager
) property provides some functions for the sessions to the WebSocket service.
The WebSocketService.Sessions.Broadcast
method sends a data to all client of the WebSocket service.
Creating an instance of the WebSocketServer
class.
var wssv = new WebSocketServer (4649);
wssv.AddWebSocketService<Echo> ("/Echo");
wssv.AddWebSocketService<Chat> ("/Chat");
wssv.AddWebSocketService<Chat> ("/ChatWithNiceBoat", () => new Chat (" Nice boat."));
You can add any WebSocket service with the specified path to the service to your WebSocketServer
by using the WebSocketServer.AddWebSocketService<TWithNew>
or WebSocketServer.AddWebSocketService<T>
method.
The type of TWithNew
must inherit the WebSocketService
class and must have a public parameterless constructor.
The type of T
must inherit WebSocketService
class.
So you can use the classes created in Step 2.
If you create an instance of the WebSocketServer
class without the port number, the WebSocketServer
set the port number to 80 automatically. So it is necessary to run with root permission.
$ sudo mono example2.exe
Starting the server.
wssv.Start ();
Stopping the server.
wssv.Stop ();
I modified the System.Net.HttpListener
, System.Net.HttpListenerContext
and some other classes of Mono to create the HTTP server that can upgrade the connection to the WebSocket connection when it receives a WebSocket connection request.
You can add any WebSocket service with the specified path to the service to your HttpServer
by using the HttpServer.AddWebSocketService<TWithNew>
or HttpServer.AddWebSocketService<T>
method.
var httpsv = new HttpServer (4649);
httpsv.AddWebSocketService<Echo> ("/Echo");
httpsv.AddWebSocketService<Chat> ("/Chat");
httpsv.AddWebSocketService<Chat> ("/ChatWithNiceBoat", () => new Chat (" Nice boat."));
For more information, could you see Example3?
websocket-sharp supports Per-message Compression extension. (But it doesn't support with extension parameters.)
If you enable this extension as a WebSocket client, you should do the following.
ws.Compression = CompressionMethod.DEFLATE;
And then your WebSocket client sends the following header in the opening handshake to a WebSocket server.
Sec-WebSocket-Extensions: permessage-deflate
If the server supports this extension, it responds the same header. And when your client receives the header, it enables this extension.
As a WebSocket Client, creating an instance of the WebSocket
class with the WebSocket URL with wss scheme.
using (var ws = new WebSocket ("wss://example.com"))
{
...
}
If you set the custom validation for the server certificate, you use the WebSocket.ServerCertificateValidationCallback
property.
ws.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) =>
{
// Do something to validate the server certificate.
return true; // The server certificate is valid.
};
If you set this property to nothing, the validation does nothing with the server certificate, always returns valid.
As a WebSocket Server, creating an instance of the WebSocketServer
or HttpServer
class with some settings for the secure connection.
var wssv = new WebSocketServer (4649, true);
wssv.Certificate = new X509Certificate2 ("/path/to/cert.pfx", "password for cert.pfx");
The WebSocket
class includes own logging functions.
The WebSocket.Log
property provides the logging functions.
If you change the current logging level (the default is LogLevel.ERROR
), you use the WebSocket.Log.Level
property.
ws.Log.Level = LogLevel.DEBUG;
The above means that the logging outputs with a less than LogLevel.DEBUG
are not outputted.
And if you output a log, you use any of some output methods. The following outputs a log with LogLevel.DEBUG
.
ws.Log.Debug ("This is a debug message.");
The WebSocketServer
and HttpServer
classes include the same logging functions.
Examples using websocket-sharp.
Example connects to the Echo server using the WebSocket.
Example1 connects to the Audio Data delivery server using the WebSocket (Example1 is only implemented the chat feature, still unfinished).
Example2 starts a WebSocket server.
Example3 starts an HTTP server that can upgrade the connection to the WebSocket connection.
Could you access to http://localhost:4649 to do WebSocket Echo Test with your web browser after Example3 running?
websocket-sharp supports RFC 6455 and is based on the following WebSocket references.
Thanks for translating to japanese.
websocket-sharp is provided under The MIT License.