Programmatic ServerEndpoint wont work within Embedded Tomcat












0















I have an embedded tomcat running and i am trying to setup websockets programmatically, can't use annotations, since i get the list of context paths dynamically. Using Java 8 and Tomcat 7.



Below is the code i am using,



Embedded Tomcat,



public class EmbeddedTomcat {
/**
* @param args
* @throws LifecycleException
*/
public static void main(String args) throws LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setPort(5555);

Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

Tomcat.addServlet(ctx, "hello", new HttpServlet() {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Writer w = resp.getWriter();
w.write("Hello World !!");
w.flush();
w.close();
}
});

ctx.addServletMapping("/hello", "hello");

ctx.addApplicationListener(WSContextListener.class.getName());

tomcat.start();
tomcat.getServer().await();
}


}



WebSocket Listener to dynamically add the endpoints,



public class WSContextListener extends WsContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
super.contextInitialized(sce);

ServerContainer sc =
(ServerContainer) sce.getServletContext().getAttribute(
Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
try {
ServerEndpointConfig endPointConfig = ServerEndpointConfig.Builder
.create(WSEndpoint.class, "/wshello")
.build();
sc.addEndpoint(endPointConfig);
} catch(DeploymentException de) {
de.printStackTrace();
}
}


}



The actual server endpoint class,



public class WSEndpoint extends Endpoint {

/* (non-Javadoc)
* @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig)
*/
@Override
public void onOpen(Session session, EndpointConfig endpointConfig) {
System.out.println(String.format("Opened a new session with Id[%s] associated to endpoint[%s]", session.getId(), session.getRequestURI().getPath()));

session.addMessageHandler(new MessageHandler.Whole<String>() {
@Override
public void onMessage(String data) {
System.out.println("Data received - " + data);
session.getAsyncRemote().sendText(data);
}
});
}

@Override
public void onClose(Session session, CloseReason closeReason) {
System.out.println(String.format("Closing the connection to endpoint[%s] for session Id[%s] ", session.getRequestURI().getPath(), session.getId()));
super.onClose(session, closeReason);
}

@Override
public void onError(Session session, Throwable throwable) {
System.out.println(String.format("Error [%s] occurred on session Id[%s] associated to endpoint[%s]", throwable.getMessage(), session.getId(), session.getRequestURI().getPath()));
super.onError(session, throwable);
}


}



Finally, the javascript bit to connect to the Websocket,



var webSocket = new WebSocket("ws://localhost:5555/wshello");


I can access the servlet (http://localhost:5555/hello) and that bit works. The moment i try accessing the websocket via the above javascript code, it fails with,




websocket_test.html:18 WebSocket connection to 'ws://localhost:5555/wshello' failed: Error during WebSocket handshake: Unexpected response code: 404











share|improve this question



























    0















    I have an embedded tomcat running and i am trying to setup websockets programmatically, can't use annotations, since i get the list of context paths dynamically. Using Java 8 and Tomcat 7.



    Below is the code i am using,



    Embedded Tomcat,



    public class EmbeddedTomcat {
    /**
    * @param args
    * @throws LifecycleException
    */
    public static void main(String args) throws LifecycleException {
    Tomcat tomcat = new Tomcat();
    tomcat.setPort(5555);

    Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

    Tomcat.addServlet(ctx, "hello", new HttpServlet() {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    Writer w = resp.getWriter();
    w.write("Hello World !!");
    w.flush();
    w.close();
    }
    });

    ctx.addServletMapping("/hello", "hello");

    ctx.addApplicationListener(WSContextListener.class.getName());

    tomcat.start();
    tomcat.getServer().await();
    }


    }



    WebSocket Listener to dynamically add the endpoints,



    public class WSContextListener extends WsContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
    super.contextInitialized(sce);

    ServerContainer sc =
    (ServerContainer) sce.getServletContext().getAttribute(
    Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
    try {
    ServerEndpointConfig endPointConfig = ServerEndpointConfig.Builder
    .create(WSEndpoint.class, "/wshello")
    .build();
    sc.addEndpoint(endPointConfig);
    } catch(DeploymentException de) {
    de.printStackTrace();
    }
    }


    }



    The actual server endpoint class,



    public class WSEndpoint extends Endpoint {

    /* (non-Javadoc)
    * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig)
    */
    @Override
    public void onOpen(Session session, EndpointConfig endpointConfig) {
    System.out.println(String.format("Opened a new session with Id[%s] associated to endpoint[%s]", session.getId(), session.getRequestURI().getPath()));

    session.addMessageHandler(new MessageHandler.Whole<String>() {
    @Override
    public void onMessage(String data) {
    System.out.println("Data received - " + data);
    session.getAsyncRemote().sendText(data);
    }
    });
    }

    @Override
    public void onClose(Session session, CloseReason closeReason) {
    System.out.println(String.format("Closing the connection to endpoint[%s] for session Id[%s] ", session.getRequestURI().getPath(), session.getId()));
    super.onClose(session, closeReason);
    }

    @Override
    public void onError(Session session, Throwable throwable) {
    System.out.println(String.format("Error [%s] occurred on session Id[%s] associated to endpoint[%s]", throwable.getMessage(), session.getId(), session.getRequestURI().getPath()));
    super.onError(session, throwable);
    }


    }



    Finally, the javascript bit to connect to the Websocket,



    var webSocket = new WebSocket("ws://localhost:5555/wshello");


    I can access the servlet (http://localhost:5555/hello) and that bit works. The moment i try accessing the websocket via the above javascript code, it fails with,




    websocket_test.html:18 WebSocket connection to 'ws://localhost:5555/wshello' failed: Error during WebSocket handshake: Unexpected response code: 404











    share|improve this question

























      0












      0








      0








      I have an embedded tomcat running and i am trying to setup websockets programmatically, can't use annotations, since i get the list of context paths dynamically. Using Java 8 and Tomcat 7.



      Below is the code i am using,



      Embedded Tomcat,



      public class EmbeddedTomcat {
      /**
      * @param args
      * @throws LifecycleException
      */
      public static void main(String args) throws LifecycleException {
      Tomcat tomcat = new Tomcat();
      tomcat.setPort(5555);

      Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

      Tomcat.addServlet(ctx, "hello", new HttpServlet() {
      @Override
      protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
      Writer w = resp.getWriter();
      w.write("Hello World !!");
      w.flush();
      w.close();
      }
      });

      ctx.addServletMapping("/hello", "hello");

      ctx.addApplicationListener(WSContextListener.class.getName());

      tomcat.start();
      tomcat.getServer().await();
      }


      }



      WebSocket Listener to dynamically add the endpoints,



      public class WSContextListener extends WsContextListener {

      @Override
      public void contextInitialized(ServletContextEvent sce) {
      super.contextInitialized(sce);

      ServerContainer sc =
      (ServerContainer) sce.getServletContext().getAttribute(
      Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
      try {
      ServerEndpointConfig endPointConfig = ServerEndpointConfig.Builder
      .create(WSEndpoint.class, "/wshello")
      .build();
      sc.addEndpoint(endPointConfig);
      } catch(DeploymentException de) {
      de.printStackTrace();
      }
      }


      }



      The actual server endpoint class,



      public class WSEndpoint extends Endpoint {

      /* (non-Javadoc)
      * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig)
      */
      @Override
      public void onOpen(Session session, EndpointConfig endpointConfig) {
      System.out.println(String.format("Opened a new session with Id[%s] associated to endpoint[%s]", session.getId(), session.getRequestURI().getPath()));

      session.addMessageHandler(new MessageHandler.Whole<String>() {
      @Override
      public void onMessage(String data) {
      System.out.println("Data received - " + data);
      session.getAsyncRemote().sendText(data);
      }
      });
      }

      @Override
      public void onClose(Session session, CloseReason closeReason) {
      System.out.println(String.format("Closing the connection to endpoint[%s] for session Id[%s] ", session.getRequestURI().getPath(), session.getId()));
      super.onClose(session, closeReason);
      }

      @Override
      public void onError(Session session, Throwable throwable) {
      System.out.println(String.format("Error [%s] occurred on session Id[%s] associated to endpoint[%s]", throwable.getMessage(), session.getId(), session.getRequestURI().getPath()));
      super.onError(session, throwable);
      }


      }



      Finally, the javascript bit to connect to the Websocket,



      var webSocket = new WebSocket("ws://localhost:5555/wshello");


      I can access the servlet (http://localhost:5555/hello) and that bit works. The moment i try accessing the websocket via the above javascript code, it fails with,




      websocket_test.html:18 WebSocket connection to 'ws://localhost:5555/wshello' failed: Error during WebSocket handshake: Unexpected response code: 404











      share|improve this question














      I have an embedded tomcat running and i am trying to setup websockets programmatically, can't use annotations, since i get the list of context paths dynamically. Using Java 8 and Tomcat 7.



      Below is the code i am using,



      Embedded Tomcat,



      public class EmbeddedTomcat {
      /**
      * @param args
      * @throws LifecycleException
      */
      public static void main(String args) throws LifecycleException {
      Tomcat tomcat = new Tomcat();
      tomcat.setPort(5555);

      Context ctx = tomcat.addContext("", new File(".").getAbsolutePath());

      Tomcat.addServlet(ctx, "hello", new HttpServlet() {
      @Override
      protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
      Writer w = resp.getWriter();
      w.write("Hello World !!");
      w.flush();
      w.close();
      }
      });

      ctx.addServletMapping("/hello", "hello");

      ctx.addApplicationListener(WSContextListener.class.getName());

      tomcat.start();
      tomcat.getServer().await();
      }


      }



      WebSocket Listener to dynamically add the endpoints,



      public class WSContextListener extends WsContextListener {

      @Override
      public void contextInitialized(ServletContextEvent sce) {
      super.contextInitialized(sce);

      ServerContainer sc =
      (ServerContainer) sce.getServletContext().getAttribute(
      Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE);
      try {
      ServerEndpointConfig endPointConfig = ServerEndpointConfig.Builder
      .create(WSEndpoint.class, "/wshello")
      .build();
      sc.addEndpoint(endPointConfig);
      } catch(DeploymentException de) {
      de.printStackTrace();
      }
      }


      }



      The actual server endpoint class,



      public class WSEndpoint extends Endpoint {

      /* (non-Javadoc)
      * @see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig)
      */
      @Override
      public void onOpen(Session session, EndpointConfig endpointConfig) {
      System.out.println(String.format("Opened a new session with Id[%s] associated to endpoint[%s]", session.getId(), session.getRequestURI().getPath()));

      session.addMessageHandler(new MessageHandler.Whole<String>() {
      @Override
      public void onMessage(String data) {
      System.out.println("Data received - " + data);
      session.getAsyncRemote().sendText(data);
      }
      });
      }

      @Override
      public void onClose(Session session, CloseReason closeReason) {
      System.out.println(String.format("Closing the connection to endpoint[%s] for session Id[%s] ", session.getRequestURI().getPath(), session.getId()));
      super.onClose(session, closeReason);
      }

      @Override
      public void onError(Session session, Throwable throwable) {
      System.out.println(String.format("Error [%s] occurred on session Id[%s] associated to endpoint[%s]", throwable.getMessage(), session.getId(), session.getRequestURI().getPath()));
      super.onError(session, throwable);
      }


      }



      Finally, the javascript bit to connect to the Websocket,



      var webSocket = new WebSocket("ws://localhost:5555/wshello");


      I can access the servlet (http://localhost:5555/hello) and that bit works. The moment i try accessing the websocket via the above javascript code, it fails with,




      websocket_test.html:18 WebSocket connection to 'ws://localhost:5555/wshello' failed: Error during WebSocket handshake: Unexpected response code: 404








      java tomcat websocket






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 26 '18 at 5:13









      VickyVicky

      3292717




      3292717
























          1 Answer
          1






          active

          oldest

          votes


















          0














          Try this



          var webSocket = new WebSocket("ws://localhost:5555/hello", "protocol");


          The protocol added to handle websocket at the client side(optional).
          Remove wshello "ws"






          share|improve this answer
























          • the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

            – Vicky
            Nov 27 '18 at 15:21













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53475084%2fprogrammatic-serverendpoint-wont-work-within-embedded-tomcat%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          Try this



          var webSocket = new WebSocket("ws://localhost:5555/hello", "protocol");


          The protocol added to handle websocket at the client side(optional).
          Remove wshello "ws"






          share|improve this answer
























          • the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

            – Vicky
            Nov 27 '18 at 15:21


















          0














          Try this



          var webSocket = new WebSocket("ws://localhost:5555/hello", "protocol");


          The protocol added to handle websocket at the client side(optional).
          Remove wshello "ws"






          share|improve this answer
























          • the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

            – Vicky
            Nov 27 '18 at 15:21
















          0












          0








          0







          Try this



          var webSocket = new WebSocket("ws://localhost:5555/hello", "protocol");


          The protocol added to handle websocket at the client side(optional).
          Remove wshello "ws"






          share|improve this answer













          Try this



          var webSocket = new WebSocket("ws://localhost:5555/hello", "protocol");


          The protocol added to handle websocket at the client side(optional).
          Remove wshello "ws"







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 26 '18 at 6:10









          薛源少薛源少

          1181318




          1181318













          • the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

            – Vicky
            Nov 27 '18 at 15:21





















          • the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

            – Vicky
            Nov 27 '18 at 15:21



















          the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

          – Vicky
          Nov 27 '18 at 15:21







          the javascript api is not an issue, since if i try hitting a public websocket server, it works. var webSocket = new WebSocket("wss://echo.websocket.org") The problem seems to be on the server end. Also the endpoint configured is "wshello" for websocket, so not sure why a servlet endpoint "hello" should be used there.

          – Vicky
          Nov 27 '18 at 15:21






















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53475084%2fprogrammatic-serverendpoint-wont-work-within-embedded-tomcat%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Ottavio Pratesi

          Tricia Helfer

          15 giugno