Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 306
ChaoSXDemon Avatar asked Dec 09 '14 23:12

ChaoSXDemon


2 Answers

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

like image 199
Vitaly Avatar answered Oct 27 '22 11:10

Vitaly


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?

like image 34
Shmil The Cat Avatar answered Oct 27 '22 13:10

Shmil The Cat