Wednesday, April 11, 2012

For a project here at OrionSoftware we needed a test application that displays realtime results to a webpage. Nice moment to digg a bit deeper in the WebSockets protocol. It only works on certain browsers so you can't demo on all browsers. At least chrome works, so that is the browser I use during this sample.

Start

We begin with the creation of a new console application project in VisualStudio 2010 and call it MyWebSocket.Change the profile to a Full .Net Profile in the project properties. I always create an assemblies map in the root of the solution and add all my external referenced assemblies in here that aren't included via nuget. Unfortunately the SuperWebSocket server library isn't in nuget at this time so I extract the binary assemblies from the Net40 map of SuperWebSocket in this map.

Now I create references to the libraries by using Add Reference - Browse - and selecting all the assemblies in the assemblies folder.

Now we create a new folder in our project and call it Views and add a new index.html view in it. Remember to set the CopyAlways property to this file. For now we leave the file as is. We will edit this file in the client section of this sample.

SuperWebSocket Server

Now create our second server which will respond to our websockets call from the client.

This will create a socketserver which reacts to three events. When a new session connection comes in it will send a message to all clients. When a session disconnects it will inform the other clients. When a message comes in it will send this message to all clients.

Here we have a simple chat client. It has an input where you can type a message and it will be distributed to all other clients when you click the button. The button will only be active when the connection to our websocket server is established.

In the jquery document ready callback we create a new WebSocket object with the url matching the server. We create three callbacks on this object. And our chat application is complete.

Run the Chat Application

When we run the application from VisualStudio we can browse with two Chrome windows to our NancyFX url: http://127.0.0.1:8080 and we can chat.