Monday, February 08, 2010

Web Socket Server

I've been hearing about HTML5 for quite some time now, and I especially liked the idea of web sockets. Giving us the ability to send data directly to the user, instead of doing something like polling with AJAX requests seems like a very neat idea.

So the other day, I decided that I would try to make a small server and test it out on my localhost. As far as I can tell, only Google Chrome supports web sockets at the moment, but I sure hope that it will pick up.

Background

The server is heavily based on sockets. I don't think you would need to be very experienced in working with sockets, but a bit of knowledge shouldn't hurt. The code is not entirely simple, I'm using a small amount of delegates and lambda expressions, but again, it’s not very hard either. I guess you'll be fine.

Using the Code

The code is organized into a couple of classes in a class library, which could be included as a project in your solution or compiled into an assembly. It’s hard to create a ready-made demo application as you need a webserver, a browser and the web socket server to run simultaneously in order for it to work. But I'll try to explain how to get it all working. The project contains two main classes: WebSocketServer and WebSocketConnection. The WebSocketServer is responsible for handling all the client connections and the initial handshaking. The WebSocketConnection handles the individual connections. The server listens for connections and creates the connection objects upon connection, and the connection objects are used to interact with the clients (sending/receiving data).

The following is an example of how you could start the server:

var wss = new WebSocketServer(8181,
                             "http://localhost:8080",
                             "ws://localhost:8181/service");
wss.Start();


Read more: Codeproject

Posted via email from jasper22's posterous