Version: 9.4.14.v20181114 |

Jetty WebSocket Server API
Previous | Chapter 27. Jetty Websocket API Home | Next

##### Contact the core Jetty developers at www.webtide.com

private support for your internal/customer projects ... custom extensions and distributions ... versioned snapshots for indefinite support ... scalability guidance for your apps and Ajax/Comet projects ... development services for sponsored feature development

## Jetty WebSocket Server API

Jetty provides the ability to wire up WebSocket endpoints to Servlet Path Specs via the use of a WebSocketServlet bridge servlet.

Internally, Jetty manages the HTTP Upgrade to WebSocket and migration from a HTTP Connection to a WebSocket Connection.

This will only work when running within the Jetty Container (unlike past Jetty technologies, you cannot get Jetty WebSocket server functionality running Jetty within other containers like JBoss, Tomcat, or WebLogic).

### The Jetty WebSocketServlet

To wire up your WebSocket to a specific path via the WebSocketServlet, you will need to extend org.eclipse.jetty.websocket.servlet.WebSocketServlet and specify what WebSocket object should be created with incoming Upgrade requests.

    //
    //  ========================================================================
    //  Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
    //  ------------------------------------------------------------------------
    //  All rights reserved. This program and the accompanying materials
    //  are made available under the terms of the Eclipse Public License v1.0
    //  and Apache License v2.0 which accompanies this distribution.
    //
    //      The Eclipse Public License is available at
    //      http://www.eclipse.org/legal/epl-v10.html
    //
    //      The Apache License v2.0 is available at
    //      http://www.opensource.org/licenses/apache2.0.php
    //
    //  You may elect to redistribute this code under either of these licenses.
    //  ========================================================================
    //

    package examples;

    import javax.servlet.annotation.WebServlet;

    import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
    import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

    @SuppressWarnings("serial")
    @WebServlet(name = "MyEcho WebSocket Servlet", urlPatterns = { "/echo" })
    public class MyEchoServlet extends WebSocketServlet
    {
        @Override
        public void configure(WebSocketServletFactory factory)
        {
            // set a 10 second timeout
            factory.getPolicy().setIdleTimeout(10000);

            // register MyEchoSocket as the WebSocket to create on Upgrade
            factory.register(MyEchoSocket.class);
        }
    }

This example will create a Servlet mapped via the @WebServlet annotation to the Servlet path spec of `"/echo"` (or you can do this manually in the `WEB-INF/web.xml` of your web application) which will create MyEchoSocket instances when encountering HTTP Upgrade requests.

The `WebSocketServlet.configure(WebSocketServletFactory factory)` is where you put your specific configuration for your WebSocket. In the example we specify a 10 second idle timeout and register MyEchoSocket with the default WebSocketCreator the WebSocket class we want to be created on Upgrade.

> ### Note

> It is important that you take in account any firewall or router timeouts when configuring websockets. Be sure the websocket configuration is lower than your firewall or router.

### Using the WebSocketCreator

All WebSocket’s are created via whatever WebSocketCreator you have registered with the WebSocketServletFactory.

By default, the WebSocketServletFactory is a simple WebSocketCreator capable of creating a single WebSocket object. Use `WebSocketCreator.register(Class<?> websocket)` to tell the WebSocketServletFactory which class it should instantiate (make sure it has a default constructor).

If you have a more complicated creation scenario, you might want to provide your own WebSocketCreator that bases the WebSocket it creates off of information present in the UpgradeRequest object.

    //
    //  ========================================================================
    //  Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
    //  ------------------------------------------------------------------------
    //  All rights reserved. This program and the accompanying materials
    //  are made available under the terms of the Eclipse Public License v1.0
    //  and Apache License v2.0 which accompanies this distribution.
    //
    //      The Eclipse Public License is available at
    //      http://www.eclipse.org/legal/epl-v10.html
    //
    //      The Apache License v2.0 is available at
    //      http://www.opensource.org/licenses/apache2.0.php
    //
    //  You may elect to redistribute this code under either of these licenses.
    //  ========================================================================
    //

    package examples;

    import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
    import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
    import org.eclipse.jetty.websocket.servlet.WebSocketCreator;

    public class MyAdvancedEchoCreator implements WebSocketCreator
    {
        private MyBinaryEchoSocket binaryEcho;
        private MyEchoSocket textEcho;

        public MyAdvancedEchoCreator()
        {
            // Create the reusable sockets
            this.binaryEcho = new MyBinaryEchoSocket();
            this.textEcho = new MyEchoSocket();
        }

        @Override
        public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp)
        {
            for (String subprotocol : req.getSubProtocols())
            {
                if ("binary".equals(subprotocol))
                {
                    resp.setAcceptedSubProtocol(subprotocol);
                    return binaryEcho;
                }
                if ("text".equals(subprotocol))
                {
                    resp.setAcceptedSubProtocol(subprotocol);
                    return textEcho;
                }
            }

            // No valid subprotocol in request, ignore the request
            return null;
        }
    }

Here we show a WebSocketCreator that will utilize the WebSocket subprotocol information from request to determine what WebSocket type should be created.

    //
    //  ========================================================================
    //  Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.
    //  ------------------------------------------------------------------------
    //  All rights reserved. This program and the accompanying materials
    //  are made available under the terms of the Eclipse Public License v1.0
    //  and Apache License v2.0 which accompanies this distribution.
    //
    //      The Eclipse Public License is available at
    //      http://www.eclipse.org/legal/epl-v10.html
    //
    //      The Apache License v2.0 is available at
    //      http://www.opensource.org/licenses/apache2.0.php
    //
    //  You may elect to redistribute this code under either of these licenses.
    //  ========================================================================
    //

    package examples;

    import javax.servlet.annotation.WebServlet;

    import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
    import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;

    @SuppressWarnings("serial")
    @WebServlet(name = "MyAdvanced Echo WebSocket Servlet", urlPatterns = { "/advecho" })
    public class MyAdvancedEchoServlet extends WebSocketServlet
    {
        @Override
        public void configure(WebSocketServletFactory factory)
        {
            // set a 10 second timeout
            factory.getPolicy().setIdleTimeout(10000);

            // set a custom WebSocket creator
            factory.setCreator(new MyAdvancedEchoCreator());
        }
    }

When you want a custom WebSocketCreator, use `WebSocketServletFactory.setCreator(WebSocketCreator creator)` and the WebSocketServletFactory will use your creator for all incoming Upgrade requests on this servlet.

Other uses for a WebSocketCreator:

- Controlling the selection of WebSocket subprotocol
- Performing any WebSocket origin you deem important.
- Obtaining the HTTP headers from incoming request
- Obtaining the Servlet HttpSession object (if it exists)
- Specifying a response status code and reason

If you don’t want to accept the upgrade, simply return null from the link:http://www.eclipse.org/jetty/javadoc/9.4.14.v20181114/org/eclipse/jetty/websocket/servlet/WebSocketCreator.html#createWebSocket(org.eclipse.jetty.websocket.api.UpgradeRequest, org.eclipse.jetty.websocket.api.UpgradeResponse)[`WebSocketCreator.createWebSocket(UpgradeRequest req, UpgradeResponse resp)`] method.

Previous | Top | Next
Using the WebSocketAdapter | Home | Jetty WebSocket Client API

See an error or something missing? Contribute to this documentation at Github!(Generated: 2018-11-14)