java – Jetty如何创建自定义WebSocket

在线查看,我发现创建套接字的方法是使用@WebSocket注释创建一个类,并使用所需的带注释的事件方法.为了使用这个套接字,使用套接字处理程序,如下所示:

import org.eclipse.jetty.websocket.server.WebSocketHandler;
import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

import rsvp.RSVPSocket;

public class RSVPWebSocketHandler extends WebSocketHandler
{

    @Override
    public void configure ( WebSocketServletFactory factory )
    {
        factory.register( MySocket.class );
    }

}

我的问题是:如果“MySocket”类有一个带参数的构造函数,我怎样才能让工厂正确调用那个?

最佳答案
您可以从servlet创建套接字.例如:

@WebServlet(name = "MyWebSocketServlet", urlPatterns = {"/myurl"})
public class MyWebSocketServlet extends WebSocketServlet {
    private final static int IDLE_TIME = 60 * 1000;

    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(IDLE_TIME);
        factory.setCreator(new CustomWebSocketCreator());
    }
}

和CustomWebSocketCreator:

public class CustomWebSocketCreator implements WebSocketCreator {

    @Override
    public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
        return new MySocket();
    }
}

更多细节:
http://www.eclipse.org/jetty/documentation/9.1.5.v20140505/jetty-websocket-server-api.html

转载注明原文:java – Jetty如何创建自定义WebSocket - 代码日志