【问题标题】:Jetty websockets and abstracthandlerJetty websockets 和 abstracthandler
【发布时间】:2018-04-24 17:46:49
【问题描述】:

我正在尝试让普通的 AbstractHandler 和 WebSocketAdapter 同时工作。

jetty 版本:jetty-9.4.8.v20171121,

我有一个简单的类Foo 扩展org.eclipse.jetty.server.handler.AbstractHandler

也是一个扩展org.eclipse.jetty.websocket.api.WebSocketAdapter的类Bar

胶水类:

@SuppressWarnings("serial")
public class Glue extends WebSocketServlet {
  @Override
  public void configure(WebSocketServletFactory factory) {
    factory.register(Bar.class);
  }
}

现在我尝试制作一个同时使用这两种方法的服务器:

ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
context.setHandler(new Foo());
ServletHolder holder = new ServletHolder("ws-events", Glue.class);
context.addServlet(holder, "/whatever/*");

Server server = new Server(80);
server.setHandler(context);
server.start();

这开始了,当我转到 localhost 时,我看到了 Foo 应该显示的内容,但我无法连接到 websocket。看起来所有请求都发送给 Foo。

当我删除 context.setHandler(new Foo()); 行时,它显然不再显示 html 内容,但我可以连接到 websocket。

我希望两者同时工作。

【问题讨论】:

    标签: jetty java-websocket


    【解决方案1】:

    不要将响应处理程序和 ServletContextHandler 混合使用。

    Foo 更改为Servlet,为其分配一个合理的url-pattern 作为Servlet。

    原因是因为您的Foo 在任何 servlet 代码之前执行。

    使用 Handler 完成此操作的唯一其他方法是让您的 Foo 处理程序 websocket 和 HTTP/1.1 升级感知,并且在检测到请求用于 WebSocket 升级时不执行。 (这是个坏主意!不要这样做!当 WebSocket over HTTP/2 到来时,它不向后兼容!)

    另外请注意,如果非 websocket 客户端在相同的 url 模式上请求 HTTP 内容,您可以让您的 Glue 类实现 doGet() 和服务 HTML。

    顺便说一句,如果您希望提供静态 html,请不要在您自己的代码中这样做。为您的ServletContextHandler 分配一个合理的“基本资源位置”并添加一个DefaultServlet 以提供与另一个 url 模式不匹配的静态资源。

    查看之前的答案:https://stackoverflow.com/a/20223103/775715

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2014-06-10
      • 1970-01-01
      • 2021-09-25
      • 2013-12-16
      • 1970-01-01
      • 2013-04-20
      相关资源
      最近更新 更多