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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.