Tuesday, June 19, 2012

Websockets on Tomcat 7

Recently I discovered Tomcat 7 supports websockets, I looked at the support and found it quite easy to use.

I have created a very simple websocket servlet that echoes the input from the user, first of all you need to create a class that extends from WebSocketServlet, then, for every subprotocol you want to handle, you need to create a subclass of the abstract MessageInbound. There you may choose to answer to text or binary messages, here is the source:

@WebServlet(urlPatterns="/testWebsocket")
public class TestWebsocket extends WebSocketServlet {
private static final long serialVersionUID = 1L;
@Override
protected StreamInbound createWebSocketInbound(String string, HttpServletRequest hsr) {
return new MessageInbound() {
@Override
protected void onBinaryMessage(ByteBuffer bb) throws IOException {
}
@Override
protected void onTextMessage(CharBuffer cb) throws IOException {
System.out.println(cb.toString());
WsOutbound outbound = getWsOutbound();
outbound.writeTextMessage(cb);
}
};
}
}

Now we can connect to the websocket from our javascript client code:

var ws = new WebSocket("ws://"+document.location.host+document.location.pathname+"/testWebsocket");
ws.onopen = function() {
console.log("Websocket Ready!!");
}
ws.onmessage= function(data) {
console.log(data.data);
}
function sendMessage() {
ws.send("Test");
}

And as simple as that we have our web sockets working for our java application deployed on Tomcat 7.