Playing with web sockets

The WebSocket is quite a cool concept that might gradually affect web as we know it. Currently to implement a real-time chat (Facebook and Gmail have one) you need to employ one of the xhr-based hacks aka COMET (i.e. long polling, xhr multipart etc.) and while these techniques will work, there are couple of problems. First of all HTTP protocol has not been designed for sustained client-server connection - keeping the connection open creates a performance penalty on each side. Secondly this is not a true two-way communication protocol, a lag of couple of hundreds of milliseconds in one direction is pretty much unavoidable. I could name couple of more issues related to the use of COMET but that's not the point. Point is Websockets are coming for a rescue! Well more like slowly crawling than coming, but still on the horizon.

With my WebSocket experiment I've decided to go a little bit beyond a 'chat application' and develop a game using only WebSockets and HTML. I (incorrectly) assumed that a simple tic-tac-toe game (aka noughts and crosses) would be cool to begin my journey with Websockets. I don't like reinventing the wheel so I've picked up a first php websocket library I could find and begin implementing the tic-tac-toe game. While I've failed to come up with a truly playable game I've learned couple of important lessons:

  • A tic-tac-toe game is effectively a turn based game thus it doesn't really benefit from WebSockets. Halfway through I've made a decision to convert my game into a red-and-blue squares game.
  • PHP might not be best suited for socket-based programming.
  • At this moment effectively ONLY Chrome supports web sockets!
  • For browsers that do not support WebSockets yet, there is a nifty flash compatibility wrapper (it will use native WebSockets if available, fall back to use WebSockets through flash)

Eventually I got my red-and-blue-square prototype game into kind of playable state but it's far from complete. After each 'game' you need to truncate a table in the database and also there is no logic to understand the win/lost condition thus you can play forever. Not a particularly useful piece of code but I decided to share it nevertheless, you can grab it on github.