user3406271
user3406271

Reputation: 11

How to have websockets with multiple context using same port (using jetty 8)

I trying to implement websocket server, requirement is to have multiple context on same port i.e.

ws://ip:8989/provider1
ws://ip:8989/provider2 

should provide two different connection but on same port.

I had followed old article How do I create an embedded WebSocket server Jetty 9? to create context handler.

I tried below code to create two seperate context

ContextHandler context = new ContextHandler();
context.setContextPath("/provider1");
context.setHandler(wsHandler);
server.addHandler(context);
ContextHandler context = new ContextHandler();
context.setContextPath("/provider2");
context.setHandler(wsHandler);
server.addHandler(context);
server.start();
server.join();

But I am getting data only on 2nd context. Is this correct implementation?

Even if i made it work I have final requirement where i have to open/create context on-the-fly i.e. after starting server with first context.

Can somebody explain to how to achieve these requirement using single port?

Upvotes: 1

Views: 1570

Answers (1)

fhuertas
fhuertas

Reputation: 5483

Your problem is that you only can have one handler in Jetty 8 Server Class becouse, there is not addHandler.

The handlers are a wrapper class and they can be configured like a matryoshka doll. This is create a handler collection (HandlerCollection) and put here both context handler. This class has addHandler method

The code is the following

// Collection 
HandlerCollection hc = new HandlerCollection();

// First context
ContextHandler context = new ContextHandler();
context.setContextPath("/provider1");
context.setHandler(wsHandler);
hc.addHandler(context)

// Second context
ContextHandler context2 = new ContextHandler();
context2.setContextPath("/provider2");
context2.setHandler(wsHandler2);
hc.addHandler(context2)


server.setHandler(hc);
server.start();
server.join();

Upvotes: 1

Related Questions