Drifting
Drifting

Reputation: 131

Define Websocket in Jetty Embedded in Karaf

I am using Apache Karaf 4.0.7 to create a server application using Websockets to communicate with a client application to send/receive data. I want to define a Websockets endpoint for the embedded Jetty server already running in Karaf.

Here is the code I have in a BundleActivator to define the Websockets endpoint. This code works and allows me to establish a connection, but the bundle hangs indefinitely in the 'Starting' state.

    public void start(BundleContext bundleContext) throws Exception {
    Server server = new Server();
    ServerConnector connector = new ServerConnector(server);
    connector.setPort(8080);
    server.addConnector(connector);

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");
    server.setHandler(context);

    try
    {
        // Initialize javax.websocket layer
        ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);

        // Add WebSocket endpoint to javax.websocket layer
        wscontainer.addEndpoint(UserWebsocketResource.class);

        server.start();
        server.dump(System.err);
        server.join();
    }
    catch (Throwable t)
    {
        t.printStackTrace(System.err);
    }
}

I am wondering if the problem is that I am creating a new Jetty server and the server.start() is creating threads which are running and not allowing the bundle to reach the 'Active' state? The current documentation on working with Jetty/Karaf is sparse, and I have the added complication of working with OSGI bundles.

Is there a better way to use websockets with embedded Jetty? Do I need to modify the PAX file in the Karaf/etc and add a new connector? All these interacting technologies are difficult to navigate for a beginning engineer!

Upvotes: 0

Views: 867

Answers (1)

Maxim Che
Maxim Che

Reputation: 76

In the example above you hang the activator by server.join(), that's why the bundle is in Starting stage.

I think that the following example is good enough to have a look how to add websocket to your bundle: https://github.com/ops4j/org.ops4j.pax.web/tree/master/samples/karaf-websocket

Upvotes: 1

Related Questions