A simple WebSockets chat

Unfortuantely this example isn't actually working due to restrictions from my web hoster.

Warning: Your browser doesn't support WebSockets.

Client side code

    $(function () {
        var ws = new WebSocket('ws://' + location.hostname + ':81/chat');
        ws.onopen = function () {
            $('<li>').text('Connection open').prependTo('#messages');
        };
        ws.onmessage = function (e) {
            $('<li>').text(e.data).prependTo('#messages');
        };
        ws.onerror = function (e) {
            $('<li>').text('Connection error').prependTo('#messages');
        };


        $('#btn').click(function () {
            var txt = $('#txt').val();
            ws.send(txt);
            $('#txt').val('').focus();
        });

    });

Server side code

This new WS and WSS protocol does mean we need some additional capabilities on the server. Depending on your technology choices you can use any number of libraries. The most popular server side implementation seems to be Socket.IO which is a Node.js based implementation. As I am a .NET developer I tend to go for a .NET library. There are different implementations, for example in WCF 4.5 or in SignalR however both of these are dependent on Windows Server 8. There is another library I tend to use at the moment called Fleck which works well but unfortunately doesn't want to share port 80 meaning that I can’t run a live example on my shared hosted site.

The required server side code for a simple chat application with Fleck is real simple:


var connections = new List<IWebSocketConnection>();
var host = System.Web.HttpContext.Current.Request.Url.Host;
var ws = new WebSocketServer("ws://" + host + ":81/chat");

ws.Start(conn =>
{
    conn.OnOpen = () =>
    {
        connections.Add(conn);
    };

    conn.OnMessage = s =>
    {
        foreach (var item in connections)
        {
            item.Send(s);
        }
    };
    conn.OnClose = () =>
    {
        connections.Remove(conn);
    };
});