ChaoSXDemon
ChaoSXDemon

Reputation: 910

Jetty How to Create Custom WebSocket

Looking around online, I have found that the way to create a socket is to create a class with the @WebSocket annotation and use the desirable annotated methods for events. In order for this socket to be used, a socket handler is used like so:

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 "MySocket" class has a constructor that has parameters, how can I make the factory invoke that one correctly?

Upvotes: 5

Views: 2671

Answers (2)

Vitaly
Vitaly

Reputation: 2662

You can create 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

Upvotes: 6

Shmil The Cat
Shmil The Cat

Reputation: 4668

According to Jetty doc you shall override createWebSocket method of your own custom derivation of the WebSocketCreator class (pass the instance of your creator to configure)

See also this answer How do I access instantiated WebSockets in Jetty 9?

Upvotes: 1

Related Questions