Friday, 1 June 2012

Websockets and the Play Framework

You'll find lots of posts about why websockets are interesting - many of them from people demonstrating them using the Play Framework. I am not going to go over any that ground but I am going to mention some example code I pulled together to demonstrate websockets in Play:

https://github.com/tomnatt/play-websocket-example

Most of the older posts are from at least 6 months ago. While the theory is right, the code examples will no longer work because the websockets specification (and hence the browser and framework implementation) has changed. In fact, I have not seen a Play 1.2.5 example yet. So here is one, mostly cobbled together from other people's older code. Shoulders of giants and all that.

Anyway, for this example you will need Play 1.2.5rc3 or above and Chrome 19+ or Firefox 12+. I haven't tested it in Java 5 but I wouldn't be surprised if Java 6 is also a requirement.

The example is the pretty basic: browser sends an event over the websocket, controller at the server end echoes it back to browser and everyone else also looking at the example page. The bit to watch out for is the handling of the event queue. The message originator has the event echoed straight back. For everyone else, the message is added to an event queue which triggers the echo via a different mechanism.

The code is over-commented so hopefully other folk can benefit from my stepping through it all.

No comments: