websocket-sharp is a C# implementation of the WebSocket protocol client & server.
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: {0}", e.Data);
};
ws.Connect();
ws.Send("BALUS");
Console.ReadKey(true);
}
}
}
}Required namespace.
using WebSocketSharp;The WebSocket class exists in the WebSocketSharp namespace.
Creating a instance of the WebSocket class.
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.
The WebSocket.OnOpen event occurs when the WebSocket connection has been established.
ws.OnOpen += (sender, e) =>
{
...
};The e has come across as the EventArgs.Empty, so there is no operation on the e.
The WebSocket.OnMessage event occurs when the WebSocket receives a data frame.
ws.OnMessage += (sender, e) =>
{
...
};The e.Type (WebSocketSharp.MessageEventArgs.Type, its type is WebSocketSharp.Opcode) indicates the Frame type of the WebSocket frame, so you check it out and you determine which item you should operate.
switch (e.Type)
{
case Opcode.TEXT:
...
break;
case Opcode.BINARY:
...
break;
default:
break;
}If the e.Type is Opcode.TEXT, you operate the e.Data (WebSocketSharp.MessageEventArgs.Data, its type is string).
If the e.Type is Opcode.BINARY, you operate the e.RawData (WebSocketSharp.MessageEventArgs.RawData, its type is byte[]).
The WebSocket.OnError event occurs when the WebSocket gets an error.
ws.OnError += (sender, e) =>
{
...
};The e.Message (WebSocketSharp.ErrorEventArgs.Message, its type is string) contains the error message, so you operate it.
The WebSocket.OnClose event occurs when the WebSocket receives a Close frame or the Close method is called.
ws.OnClose += (sender, e) =>
{
...
};The e.Code (WebSocketSharp.CloseEventArgs.Code, its type is ushort) contains a status code indicating a reason for closure and the e.Reason (WebSocketSharp.CloseEventArgs.Reason, its type is string) contains a reason for closure, so you operate them.
Connecting to the WebSocket server.
ws.Connect();Sending a data.
ws.Send(data);The Send method is overloaded.
The types of data are string, byte[] or FileInfo class.
Closing the WebSocket connection.
ws.Close(code, reason);If you want to close the WebSocket connection explicitly, you can use the Close method.
The Close method is overloaded.
The types of code are WebSocketSharp.CloseStatusCode and ushort, the type of reason is string.
In addition, the Close() and Close(code) methods exist.
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
namespace Example {
public class Laputa : WebSocketService
{
protected override void OnMessage(MessageEventArgs e)
{
var msg = e.Data.Equals("balus", StringComparison.InvariantCultureIgnoreCase)
? "I've been balused already..."
: "I'm not available now.";
Send(msg);
}
}
public class Program {
public static void Main(string[] args)
{
var wssv = new WebSocketServiceHost<Laputa>("ws://dragonsnest.far/Laputa");
wssv.Start();
Console.ReadKey(true);
wssv.Stop();
}
}
}Required namespace.
using WebSocketSharp.Server;The WebSocketServer, WebSocketServiceHost<T> and WebSocketService classes exist in the WebSocketSharp.Server namespace.
Creating a class that inherits the WebSocketService class.
For example, if you want to provide the echo service,
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Echo : WebSocketService
{
protected override void OnMessage(MessageEventArgs e)
{
Send(e.Data);
}
}Or if you want to provide the chat service,
using System;
using WebSocketSharp;
using WebSocketSharp.Server;
public class Chat : WebSocketService
{
protected override void OnMessage(MessageEventArgs e)
{
Broadcast(e.Data);
}
}If you override the OnMessage method, it is bound to the server side WebSocket.OnMessage event.
In addition, if you override the OnOpen, OnError and OnClose methods, each of them is bound to the WebSocket.OnOpen, WebSocket.OnError and WebSocket.OnClose events.
Creating a instance of the WebSocketServiceHost<T> class if you want the single WebSocket service server.
var wssv = new WebSocketServiceHost<Echo>("ws://example.com:4649");Creating a instance of the WebSocketServer class if you want the multi WebSocket service server.
var wssv = new WebSocketServer(4649);
wssv.AddWebSocketService<Echo>("/Echo");
wssv.AddWebSocketService<Chat>("/Chat");You can add to your WebSocketServer any WebSocket service and a matching path to that service by using the WebSocketServer.AddWebSocketService<T> method.
The type of T inherits WebSocketService class, so you can use a class that was created in Step 2.
If you create a instance of the WebSocketServer class without port number, WebSocketServer set 80 to port number automatically.
So it is necessary to run with root permission.
$ sudo mono example2.exe
Setting the event.
The WebSocketServiceHost<T>.OnError event occurs when the WebSocketServiceHost<T> gets an error.
wssv.OnError += (sender, e) =>
{
...
};The e.Message (WebSocketSharp.ErrorEventArgs.Message, its type is string) contains the error message, so you operate it.
Same as the WebSocketServiceHost<T>.OnError event.
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 receives a WebSocket request.
You can add to your HttpServer any WebSocket service and a matching path to that service by using the HttpServer.AddWebSocketService<T> method.
var httpsv = new HttpServer(4649);
httpsv.AddWebSocketService<Echo>("/");For more information, please refer to the Example3.
Examples of 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 a chat feature, still unfinished).
Example2 starts the WebSocket server.
Example3 starts the HTTP server that can upgrade the connection to the WebSocket connection.
Please access http://localhost:4649 to do WebSocket Echo Test with your web browser after Example3 running.
websocket-sharp supports RFC 6455.
- branch: hybi-00 supports older draft-ietf-hybi-thewebsocketprotocol-00 ( hybi-00 ).
- branch: draft75 supports even more old draft-hixie-thewebsocketprotocol-75 ( hixie-75 ).
Thx for translating to japanese.
Copyright © 2010 - 2013 sta.blockhead
Licensed under the MIT License.