Skip to main content

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [List Home]
[jetty-users] problem with adding websocket endpoints programmatically

Hi all,
It seems that adding websocket endpoints programmatically (via ServerContainer.addEndpoint) does not work in jetty-10.0.x or at least I can't get it to work ;-]
Here is the code from my ServletContextListener:

> 	public void contextInitialized(ServletContextEvent event) {
> 		try {
> 			var container = ((ServerContainer) event.getServletContext().getAttribute(
> 				"javax.websocket.server.ServerContainer"));
> 			container.addEndpoint(
> 				ServerEndpointConfig.Builder.create(EchoEndpoint.class, "/websocket/echo").build());
> 		} catch (Exception e) {
> 			System.err.println("adding endpoint failed: " + e);
> 		}
> 	}

...and here is the endpoint just in case:

> //@ServerEndpoint("/websocket/echo")
> public class EchoEndpoint {
> 
> 	Session session;
> 
> 	public EchoEndpoint() { System.out.println("new endpoint instance created"); }
> 
> 	@OnOpen
> 	public void onOpen(Session session) {
> 		System.out.println("new session opened: " + session.getId());
> 		this.session = session;
> 		session.setMaxIdleTimeout(5l * 60l * 1000l);
> 	}
> 
> 	@OnMessage
> 	public void onMessage(String message) { session.getAsyncRemote().sendText(message); }
> }

each time the browser app attempts to open a websocket, the container will create a new endpoint instance (`new endpoint instance created` message from the constructor will appear on the console), but the `onOpen` method will not get called (the message from the method does not appear on the console) and the server will close the socket immediately. no sign of any exception stacktrace on the console.

However, if the `@ServerEndpoint` annotation is uncommented at the top of the `EchoEndpoint` and the `ServletContextListener` is removed, then everything works ok.

you can see the whole app at https://github.com/morgwai/jetty-websocket

am I doing something wrong or is it some bug in Jetty?

I've tried Jetty versions 10.0.0 and 10.0.2 running on openjdk-11 on ubuntu-18.04

Thanks!


Back to the top