How to create a custom WebSocket

Looking around the internet I found that the way to create a socket is to create a class annotated with @WebSocket and use the desired annotated methods for events. To use this socket, the socket handler is used like this:

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

}

      

My question is, if the class "MySocket" has a constructor with parameters, how can I get the factory to call this file correctly?

+3


source to share


2 answers


You can create a socket from your servlet. For example:

@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());
    }
}

      

And CustomWebSocketCreator:



public class CustomWebSocketCreator implements WebSocketCreator {

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

      

More details: http://www.eclipse.org/jetty/documentation/9.1.5.v20140505/jetty-websocket-server-api.html

+4


source


According to the Jetty doc you should override the createWebSocket

class's own custom inference method WebSocketCreator

(pass the instance to your creator configure

)



See also this answer How to access instances of WebSockets in Jetty 9?

+1


source







All Articles