Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C#

WebSocket Libraries Comparison

Rate me:
Please Sign up or sign in to vote.
4.82/5 (23 votes)
2 Jun 2014CPOL8 min read 132.2K   31   30
WebSocket Libraries comparison

Web project often requires to push data to clients as fast as possible, whenever it is necessary without waiting for client request. It is perfect for website with real time communication between users, like with online communicators for example. Or document collaboration tools. Or maybe system status updates on long running calculation/tasks performed by server. In every case, two way communication mechanism is ideal.

Before, the following solution was used for this kind of problem:

But now we have something better: WebSocket. Standard is implemented for some time now in modern browsers. It was released in 2011, which is even better because with changes and upgrades, we have a more secure and mature protocol.

Few Remarks

Comparison was made few months ago and can be outdated a bit, but I think that is still useful if anyone will be looking for a good WebSocket library.

Only libraries published as NuGet packages were taken into account, beside one, SuperWebSocket which I found using NuGet repository, but it was needed to download from web page anyway.

Maybe if I will find time, I will update this article with new libraries or a new version of already tested libraries.

1. Fleck

https://github.com/statianzo/Fleck

I did find it really simple to install and use. I did not have any problems with library, documentation, examples, etc. Just add package, copy some samples and run project. Simple!

But with simplicity, there is a price: it is not very powerful nor configurable solution.

C#
private static void Main(string[] args)
{
     var server = new WebSocketServer("ws://localhost:8181");
     server.Start(socket =>
     {
          socket.OnOpen = () => OnOpen(socket);
          socket.OnClose = () => OnClose(socket);
          socket.OnMessage = m => OnMessage(socket, m);
     });
}

I would use this library for a quick or simple project. If you do not need complex data structure to be sent through WebSocket, command-like messages, many servers or fallback when your client does not have WebSocket support, this may be the library for you.

Advantages

Disadvantages

  • Simple
  • No dependencies
  • Not very configurable
  • No fallback in case your browser does not support WebSocket

2. SignalR

http://www.asp.net/signalr

It is a library from Microsoft which I personally treat as an advantage. It has integration with existing framework, ASP.NET and good abstraction for both: client and server code. It means that you do not have to know much about a protocol which is good. And it is able to fallback gracefully to other communication mechanism whenever your client cannot use WebSocket. Also, it is possible to accomplish something that is called Remote Procedure Call, from server to client.

Image 2

It can broadcast data to all clients or send message to only one. And scale to really great number of simultaneous connections. And it is open source!

Sounds really great, right? Yeah... except it needs IIS8 on Windows Server 2012 (or Windows 8 for that matter, but you would not host any really big project on that system, right?). For me, it is one of the cool features of ‘Microsoft-new-server-OS-which-you-should-buy’. It is not bad if you want to develop enterprise project, but for small projects, this library is too expensive even if it is open source.

Of course, these requirements are actually needed if you want WebSocket communication. But this article is about WebSocket communication, so I count this as really big disadvantage.

C#
public class MyHub1 : Hub
{
    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }
} 
JavaScript
$(function () {
    var chat = $.connection.myHub1;
    chat.client.broadcastMessage = function (name, message) {
        //...
    };
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            chat.server.send('message');
        });
    });
});

Advantages

Disadvantages

  • Good abstraction
  • Good integration with IIS and ASP.NET
  • Many fallbacks
  • Open source
  • Microsoft library
  • Scalable
  • IIS 8 required…
  • … which needs very expensive server OS, Windows Server 2012

3. AlchemyWebSocket

http://alchemywebsockets.net/

This one does not really comes to mind when I recall WebSocket libraries. There is nothing wrong with this one really. It can be placed right behind Fleck. It is also very simple, easy to use, easy to install (Nuget package available) and has documentation with good examples.

It has server part and client part code built-in. It is also scalable.

C#
static void Main(string[] args)
{
    // instantiate a new server - acceptable port and IP range,
    // and set up your methods.

    var aServer = new WebSocketServer(81, IPAddress.Any)
    {
        OnReceive = OnReceive,
        OnSend = OnSend,
        OnConnect = OnConnect,
        OnConnected = OnConnected,
        OnDisconnect = OnDisconnect,
        TimeOut = new TimeSpan(0, 5, 0)
    };

    aServer.Start();
    string consoleReadLine;
    do
    {
        consoleReadLine = Console.ReadLine();
        sockets.ForEach(s => s.Send(consoleReadLine));
    } while (consoleReadLine != "exit");
}

But it also has some awkwardness, that I cannot shake off. For example, there is no simple event method “OnReceive” with just string, with actual message that was sent from client. You have to do it yourself. Yes, you have to call only .ToString() to get the actual message, but the whole point of using a library is to not force yourself to think about how communication protocol is implemented.

C#
private static void OnReceive(UserContext context)
{
    Console.WriteLine("Client " + context.ClientAddress.ToString() + 
                      " sended: " + context.DataFrame.ToString());
}

WebSocket server initialization method takes first port and then IP setting. I always think, in terms of address as IP and THEN port, if port is necessary. Or timeout setting: why there is timeout anyway? I can understand that it may be sometimes useful, but as a feature not as one of primary settings. But those are details really.

For me, this forces your code to abstract it away, with another layer of code, which should be done by this library in the first place.

Anyway, you can try it out, compare performance to Fleck, and decide which would be better for your simple project.

Advantages

Disadvantages

  • Simple
  • No dependencies
  • Good documentation
  • A bit awkward and little more complicated from Fleck
  • No fallback

4. XSockets

http://xsockets.net/

This one seemed really promising. I tried hard and spend much more time, trying to make it work than on other libraries (even with performance tests, etc.). But I had no luck unfortunately. Really, anything I can think of which can be wrong with library is wrong with this one. Bad documentation which differs from code. Which one is outdated? Code or documentation? It is not easy to install and get it running. In fact, this library has examples that I had a hard time to build and run. Or examples that you could say, shows more about MVC framework than about XSockets library itself. I tried to run this inside ASP.NET project, MVC and WinService. Sadly, none of them worked.

I really hoped for this one but eventually gave up in favor of better (read any other) library. Seriously, why use a library that is hard to even start a simple project? You can predict more issues to come while actually using it inside a project. I recommend to stay away from this project.

C#
public static class XSocketsBootstrap
{
    private static IXBaseServerContainer wss;
    public static void Start()
    {            
        wss = XSockets.Plugin.Framework.Composable.GetExport();
        wss.StartServers();
    }
}

Advantages

Disadvantages

  • Seems powerful
  • Should have good JavaScript integration
  • Complicated and hard
  • Complicated to configure and run inside of WebForms, MVC and WinService
  • Differences between code and documentation
  • Outdated documentation and examples

5. Microsoft.WebSocket

http://msdn.microsoft.com/en-us/hh969243.aspx

Another library from Microsoft. And it requires IIS 8 too, so I did not have a means to test it. Examples are really low level, so it forces you to deal with buffers and streams instead of strings. In some cases, this can be good, but mostly there is no point. If you have IIS 8 on server, why bother with this library if you can use SignalR, which will take care of most of the stuff for you.

I think this is more of a proof-of-concept then a usable library.

C#
int count = receiveResult.Count;

while (receiveResult.EndOfMessage == false)
{
    if (count >= maxMessageSize)
    {
        string closeMessage = string.Format("Maximum message size: {0} bytes.", maxMessageSize);
        await socket.CloseAsync(WebSocketCloseStatus.MessageTooBig, 
                                closeMessage, CancellationToken.None);
        return;
    } receiveResult = await socket.ReceiveAsync(new ArraySegment
                      (receiveBuffer, count, maxMessageSize - count), CancellationToken.None);
    count += receiveResult.Count;
} var receivedString = Encoding.UTF8.GetString(receiveBuffer, 0, count);
var echoString = "You said " + receivedString;
ArraySegment outputBuffer = new ArraySegment(Encoding.UTF8.GetBytes(echoString));
await socket.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);

6. SuperWebsocket

http://superwebsocket.codeplex.com/

Last but not least is SuperWebsocket. I was a bit skeptical about this one (if I remember correctly, this is only one package that I somehow found through NuGet website but is not available as a package). It may seem a little complicated, but in fact it is very easy. Examples supported by documentation take you step by step from simplest WebSocket servers, to more complicated ones, with command requests, JSON, multiple servers instances, .config file configuration and more.

This library maybe does not have all cool features that others have, but it does not matter because it is very configurable and easy to make it do what you want to. It can work in ASP.NET, as console application, and Windows service. Documentation however recommends running server as system service. I from my experience recommend not running it inside web application because of slowness of such solution (very bad performance, about fifty times slower than console app). From other hand standalone application with server, requires to run .exe that is not strictly part of library, but part of SuperSocket project (on which SuperWebSocket is based). This forces you to do a little ‘magic’ to start server with debug session, or to enable debug at all. When you run server as application which is not strictly part of solution, there is also an issue with forcing server to use the latest version of assemblies from other projects.

In return, you get a well known solution for flexible WebSocket.

It is also open source, so you can change something if you want.

On the other hand, as a disadvantage, you can count lack of JavaScript client for this server (but there is C# client). Also, this one has third party dependencies.

After working with this library for a few months, I do not know about any major issues.

Advantages

Disadvantages

  • Nice features and very configurable
  • Great examples
  • Example (with documentation of recommended setup)
  • Can work as WinService and inside ASP.NET and console app
  • Good performance
  • No fallback communication
  • Dependencies

Summary

For complicated solutions/projects, I recommend use of SuperWebSocket which is stable and very configurable library. For simple and fast projects, I would choose Fleck, but I would give up both for SignalR if have the means to use the latest Windows Server as machine for tests and production.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Poland Poland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFleck poor performance Pin
manit772-Apr-17 13:19
manit772-Apr-17 13:19 
Questionabout RMI Framework ?? Pin
thangnt8415-Mar-16 21:52
professionalthangnt8415-Mar-16 21:52 
AnswerRe: about RMI Framework ?? Pin
n.podbielski17-Mar-16 1:32
n.podbielski17-Mar-16 1:32 
QuestionSignalR console client on Windows 7 Pin
YoramKosover24-Aug-15 4:51
YoramKosover24-Aug-15 4:51 
AnswerRe: SignalR console client on Windows 7 Pin
n.podbielski10-Sep-15 2:03
n.podbielski10-Sep-15 2:03 
GeneralThanks for the article Pin
shaijujanardhanan15-Jun-15 19:03
shaijujanardhanan15-Jun-15 19:03 
QuestionWhat's about SpikeEngine? Pin
ChrnoLove11-Jan-15 21:57
ChrnoLove11-Jan-15 21:57 
AnswerRe: What's about SpikeEngine? Pin
n.podbielski14-Jan-15 23:23
n.podbielski14-Jan-15 23:23 
GeneralMy vote of 5 Pin
Vijay Chauhan31-Dec-14 22:25
Vijay Chauhan31-Dec-14 22:25 
SuggestionSignalR does not need IIS8 Pin
Kim Togo11-Jun-14 0:50
professionalKim Togo11-Jun-14 0:50 
GeneralRe: SignalR does not need IIS8 Pin
n.podbielski11-Jun-14 2:05
n.podbielski11-Jun-14 2:05 
GeneralRe: SignalR does not need IIS8 Pin
Kim Togo11-Jun-14 21:44
professionalKim Togo11-Jun-14 21:44 
GeneralRe: SignalR does not need IIS8 Pin
n.podbielski11-Jun-14 23:13
n.podbielski11-Jun-14 23:13 
AnswerRe: SignalR does not need IIS8 Pin
stixoffire14-Sep-15 11:19
stixoffire14-Sep-15 11:19 
GeneralRe: SignalR does not need IIS8 Pin
n.podbielski14-Sep-15 21:51
n.podbielski14-Sep-15 21:51 
QuestionSecured websockets, websocket-sharp Pin
uaichiuu3-Jun-14 3:25
professionaluaichiuu3-Jun-14 3:25 
AnswerRe: Secured websockets, websocket-sharp Pin
n.podbielski3-Jun-14 21:22
n.podbielski3-Jun-14 21:22 
QuestionThanks for this Pin
thatraja3-Jun-14 0:45
professionalthatraja3-Jun-14 0:45 
QuestionXSockets is very, very simple to use, but documentation sucks!!! Pin
Felipe R. Machado30-May-14 17:25
professionalFelipe R. Machado30-May-14 17:25 
AnswerRe: XSockets is very, very simple to use, but documentation sucks!!! Pin
n.podbielski1-Jun-14 23:34
n.podbielski1-Jun-14 23:34 
GeneralThank you! Pin
Joakim Gyllstedt13-May-14 20:50
Joakim Gyllstedt13-May-14 20:50 
GeneralRe: Thank you! Pin
n.podbielski16-May-14 1:44
n.podbielski16-May-14 1:44 
I am glad you liked it Smile | :)
No more Mister Nice Guy... >: |

QuestionImpressed! Pin
Member 1062703726-Feb-14 0:58
Member 1062703726-Feb-14 0:58 
AnswerRe: Impressed! Pin
n.podbielski26-Feb-14 12:42
n.podbielski26-Feb-14 12:42 
GeneralRe: Impressed! Pin
FrankSchreiber16-Apr-14 19:32
FrankSchreiber16-Apr-14 19:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.