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:


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


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

8 comments:

  1. Hi I implemented that. But I never get the sendMessage called. But Websocket Ready!! is printed in js console. Why is that?

    Thanks..!!

    ReplyDelete
    Replies
    1. Umm.. did you ever write any code to actually call the sendMessage() function? Just asking...

      Delete
    2. The sendMessage() function is there to be called within the javascript console of your browser.

      Delete
  2. The sendMessage function is there for you to call from a button or another javascript event, or also you may call it within the console by just typing sendMessage()

    ReplyDelete
  3. The sendMessage function is there for you to call from a button or another javascript event, or also you may call it within the console by just typing sendMessage()

    ReplyDelete
  4. If I want sent message from server to several clients. How to do that??

    ReplyDelete
    Replies
    1. You may keep and maintain somewhere the MessageInbound instances you are creating, then just go over this collection and ask for the wsOutbound to send the message to each client.

      Delete
  5. Hello, Can you please post the maven dependencies for the source code shown above? Thanks.

    ReplyDelete