Google

Friday, December 10, 2010

WebSockets

It's been a really long time since I made a post on my blog, but lately I had to do some work that resulted in me implementing a draft spec of the WebSocket protocol. I have noticed that there is a lot of talk about them due to the development of HTML5. So I sat down with the latest draft spec for the WebSocket protocol, draft-ietf-thewebsocketprotocol-03, and began implementing a solution that more completely represented the spec and was also usable.

While I wanted to implement the full spec, I did decide to leave out a few parts. I did not implement support for Framing, which at the time of writing is not possible from the WebSocket API for JavaScript. Since my implementation was intended to communicate with browsers, and the API does not have a way for JS code to tell the socket to send data Framed. Because of that, I left it out. I have also not added support for wss, encrypted connections. I will add this at a later time.

So lets get to what I did implement. The WebSocketServer class can listen on a defined IP and port. It will listen for connection attempts and Create WebSocket objects to handle each connection. So unlike a number of sources on the net, this will handle multiple connections at one time. At this time I have not set a limit to the number of them that can be open at one time. The WebSocket class handles the connection from that point on. It will perform the handshake response to the client to establish a good connection. I will then listen for data from the client and raise an event when a complete message has been received. It also provides a way to send data to the client. The code also takes care of dropped connections by cleaning up after a connection failure.

The current code can be found here.

Let me know any suggestions you may have.