将 ServerEndpoint 添加到没有注释的 Tomcat 实例

Add ServerEndpoint to Tomcat instance without annotations

如何在不使用 [=16] 的情况下为特定 class 添加 ServerEndpointOnOpenOnMessageOnClose 事件处理程序=]、@OnOpen@OnMessage@OnClose 注释在各自的 class 中,使用嵌入的 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 我不确定这样做是否正确。

一种替代方法是扩展 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);
        }
      }
  });
}