How do I create an embedded WebSocket server Jetty 9?

Update: Dec 2, 2013

For an up to date example of the Embedded Jetty with WebSocket see:

https://github.com/jetty-project/embedded-jetty-websocket-examples

Original Answer

There’s an example found in the test cases.

http://git.eclipse.org/c/jetty/org.eclipse.jetty.project.git/tree/jetty-websocket/websocket-server/src/test/java/org/eclipse/jetty/websocket/server/examples/echo/ExampleEchoServer.java

Short Answer:

Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler()
    {
        @Override
        public void configure(WebSocketServletFactory factory)
        {
            factory.register(MyEchoSocket.class);
        }
    };
server.addHandler(wsHandler);
server.start();
server.join();

This will create a simple server that handles 1 context, the root context.

http://localhost:8080/

If you want to bind the WebSocketHandler to another context, wrap it in a ContextHandler.

Server server = new Server(8080);
WebSocketHandler wsHandler = new WebSocketHandler()
    {
        @Override
        public void configure(WebSocketServletFactory factory)
        {
            factory.register(MyEchoSocket.class);
        }
    };
ContextHandler context = new ContextHandler();
context.setContextPath("/echo");
context.setHandler(wsHandler);
server.addHandler(context);
server.start();
server.join();

This will bind your websocket to

http://localhost:8080/echo/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)