Search code examples
javatomcatwebsocketembedded-tomcat-7embedded-tomcat-8

Add ServerEndpoint to Tomcat instance without annotations


How do I add a ServerEndpoint and OnOpen, OnMessage and OnClose event handlers for a specific class without the use of @ServerEndpoint("/myUrl"), @OnOpen, @OnMessage, @OnClose annotations within the respective class, using embedded tomcat?

I believe it's something along the lines of:

Tomcat tomcat = new Tomcat();
tomcat.setPort(8080);
Context context = tomcat.addWebapp("/", new File(webappDir).getAbsolutePath());
context.setSessionTimeout(10080);
ServerContainer serverContainer = (ServerContainer) context.getServletContext().getAttribute(ServerContainer.class.getName());
ServerEndpointConfig serverEndpointConfig = ServerEndpointConfig.Builder.create(MyClass.class, "myUrl").build();
serverContainer.addEndpoint(serverEndpointConfig);

But serverContainer gives you java.lang.NullPointerException and I'm not sure if it's the correct way of doing it or not.


Solution

  • One alternative is to extend javax.websocket.Endpoint:

    https://blogs.oracle.com/arungupta/entry/websocket_client_and_server_endpoint

    public class MyEndpoint extends Endpoint {
    
      @Override
      public void onOpen(final Session session, EndpointConfig ec) {
        session.addMessageHandler(new MessageHandler.Whole<String>() {
    
          @Override
          public void onMessage(String text) {
            try {
              session.getBasicRemote().sendText(text);
            } catch (IOException ex) {
              Logger.getLogger(MyEndpoint.class.getName()).log(Level.SEVERE, null, ex);
            }
          }
      });
    }