Question

I am trying to implement a web socket through servlet. My app server is tomcat 7.

I could find examples, where WebSocketServlet class is used. But this class is deprecated and removed in tomcat 8.

I see another alternative, which is to annotate the class with the following

@ServerEndpoint(value = "/websocket/test")

I need helpin understanding,

  1. How will I use this annotation in servlets? Are servlets irrelevent in case of web sockets?
  2. If I create a normal class with the above annotation, and other annotation like onOpen,onClose etc, should I need to put the entry for that class in web.xml? Or are web.xmls are irrelevant too?

Any hello world link will also be very helpful.

Thank you. ============Edited==================== I have tried the chat example found in this link http://svn.apache.org/viewvc/tomcat/trunk/webapps/examples/WEB-INF/classes/websocket/

But when I try to invoke the socket through javascript, the events are not reaching my server at all....

Was it helpful?

Solution

Finally I figured this out. So I am answering here for others to refer.

1)How will I use this annotation in servlets? Are servlets irrelevent in case of web sockets?

Apparently yes, we don't need servlets for web sockets.

2)If I create a normal class with the above annotation, and other annotation like onOpen,onClose etc, should I need to put the entry for that class in web.xml? Or are web.xmls are irrelevant too?

No entry needed in web.xml either.

Following, is a sample server side code.

@ServerEndpoint(value = "/echo")
public class Echo {

    @OnOpen
    public void start(Session session) {
        //TODO
    }

    @OnClose
    public void end() {
        //TODO
    }

    @OnMessage
    public void incoming(String message) {
        //TODO
    }

    @OnError
    public void onError(Throwable t) throws Throwable {
        //TODO
    }

}

For client, either you can use Javascript is you have a HTML5 compatible browser. Else you write java clients using the tyrus library. Refer here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top