【问题标题】:Add ServerEndpoint to Tomcat instance without annotations在没有注释的情况下将 ServerEndpoint 添加到 Tomcat 实例
【发布时间】:2015-07-08 20:45:35
【问题描述】:

如何在不使用@ServerEndpoint("/myUrl")@OnOpen@OnMessage@OnClose 注释的情况下为特定类添加ServerEndpointOnOpenOnMessageOnClose 事件处理程序相应的类,使用嵌入式 tomcat?

我相信它是这样的:

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);

但是serverContainer 给你java.lang.NullPointerException 我不确定这是否是正确的做法。

【问题讨论】:

    标签: java tomcat websocket embedded-tomcat-7 embedded-tomcat-8


    【解决方案1】:

    另一种选择是扩展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);
            }
          }
      });
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-18
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多