15.2. Create a WebSocket Application


A WebSocket application requires the following components and configuration changes:
  • A Java client or a WebSocket enabled HTML client. You can verify HTML client browser support at this location: http://caniuse.com/websockets
  • A WebSocket server endpoint class.
  • A jboss-web.xml file configured to enable WebSockets.
  • Project dependencies configured to declare a dependency on the WebSocket API.
  • Enable the NIO2 connector in the web subsystem of the JBoss EAP server configuration file. If you installed the Native Components for your operating system with the JBoss EAP installation and have also installed Apache Portability Runtime (APR), you can instead choose to enable the APR connector.

Note

WebSocket applications require Java Runtime Environment version 7 or greater. Otherwise the WebSocket will not be enabled.

Procedure 15.1. Create the WebSocket Application

The following is a simple example of a WebSocket application. It provides buttons to open a connection, send a message, and close a connection. It does not implement any other functions or include any error handling, which would be required for a real world application.
  1. Create the JavaScript HTML client.

    The following is an example of a WebSocket client. It contains these JavaScript functions:
    • connect(): This function creates the WebSocket connection passing the WebSocket URI. The resource location matches the resource defined in the server endpoint class. This function also intercepts and handles the WebSocket onopen, onmessage, onerror, and onclose.
    • sendMessage(): This function gets the name entered in the form, creates a message, and sends it using a WebSocket.send() command.
    • disconnect(): This function issues the WebSocket.close() command.
    • displayMessage(): This function sets the display message on the page to the value returned by the WebSocket endpoint method.
    • displayStatus(): This function displays the WebSocket connection status.
    l
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
        <head>
            <title>WebSocket: Say Hello</title>
            <link rel="stylesheet" type="text/css" href="resources/css/hello.css" />
            <script type="text/javascript">
                var websocket = null;
    
                function connect() {
                    var wsURI = 'ws://' + window.location.host + '/jboss-websocket-hello/websocket/helloName';
                    websocket = new WebSocket(wsURI);
    
                    websocket.onopen = function() {
                        displayStatus('Open');
                        document.getElementById('sayHello').disabled = false;
                        displayMessage('Connection is now open. Type a name and click Say Hello to send a message.');
                    };
                    websocket.onmessage = function(event) {
                        // log the event                
                        displayMessage('The response was received! ' + event.data, 'success');
                    };
                    websocket.onerror = function(event) {
                        // log the event
                        displayMessage('Error! ' + event.data, 'error');
                    };
                    websocket.onclose = function() {
                        displayStatus('Closed');
                        displayMessage('The connection was closed or timed out. Please click the Open Connection button to reconnect.');
                        document.getElementById('sayHello').disabled = true;
                    };
                }
    
                function disconnect() {
                    if (websocket !== null) {
                        websocket.close();
                        websocket = null;
                    }
                    message.setAttribute("class", "message");
                    message.value = 'WebSocket closed.';
                    // log the event
                }
    
                function sendMessage() {
                    if (websocket !== null) {
                        var content = document.getElementById('name').value;
                        websocket.send(content);
                    } else {
                        displayMessage('WebSocket connection is not established. Please click the Open Connection button.', 'error');
                    }
                }
    
                function displayMessage(data, style) {
                    var message = document.getElementById('hellomessage');
                    message.setAttribute("class", style);
                    message.value = data;
                }
    
                function displayStatus(status) {
                    var currentStatus = document.getElementById('currentstatus');
                    currentStatus.value = status;
                }
    
            </script>
        </head>
        <body>
    
            <div>
                <h1>Welcome to JBoss!</h1>
                <div>This is a simple example of a WebSocket implementation.</div>
                <div id="connect-container">
                    <div>
                        <fieldset>
                            <legend>Connect or disconnect using WebSocket :</legend>
                            <input type="button" id="connect" onclick="connect();" value="Open Connection" />
                            <input type="button" id="disconnect" onclick="disconnect();" value="Close Connection" />
                        </fieldset>
                    </div>
                    <div>
                        <fieldset>
                            <legend>Type your name below. then click the `Say Hello` button :</legend>
                            <input id="name" type="text" size="40" style="width: 40%"/>
                            <input type="button" id="sayHello" onclick="sendMessage();" value="Say Hello" disabled="disabled"/>
                        </fieldset>
                    </div>
                    <div>Current WebSocket Connection Status: <output id="currentstatus" class="message">Closed</output></div>
                    <div>
                        <output id="hellomessage" />
                    </div>
                </div>
            </div>
        </body>
    </html>
  2. Create the WebSocket server endpoint.

    You can create a WebSocket server endpoint using either of the following methods.
    • Programmatic Endpoint: The endpoint extends the Endpoint class.
    • Annotated Endpoint: The endpoint class uses annotations to interact with the WebSocket events. It is simpler to code than the programmatic endpoint
    The code example below uses the annotated endpoint approach and handles the following events.
    • The @ServerEndpoint annotation identifies this class as a WebSocket server endpoint and specifies the path.
    • The @OnOpen annotation is triggered when the WebSocket connection is opened.
    • The @OnMessage annotation is triggered when a message is sent to the WebSocket connection.
    • The @OnClose annotation is triggered when the WebSocket connection is closed.
    package org.jboss.as.quickstarts.websocket_hello;
    
    import javax.websocket.CloseReason;
    import javax.websocket.OnClose;
    import javax.websocket.OnMessage;
    import javax.websocket.OnOpen;
    import javax.websocket.Session;
    import javax.websocket.server.ServerEndpoint;
    
    @ServerEndpoint("/websocket/helloName")
    public class HelloName {
    
        @OnMessage
        public String sayHello(String name) {
            System.out.println("Say hello to '" + name + "'");
            return ("Hello" + name);    
        }
    
        @OnOpen
        public void helloOnOpen(Session session) {
            System.out.println("WebSocket opened: " + session.getId());
        }
        
        @OnClose
        public void helloOnClose(CloseReason reason) {
            System.out.println("Closing a WebSocket due to " + reason.getReasonPhrase());
        }
    }
    
  3. Configure the jboss-web.xml file.

    You must create the <enable-websockets> element in the application WEB-INF/jboss-web.xml and set it to true.
    <?xml version="1.0" encoding="UTF-8"?>
    <!--Enable WebSockets -->
    <jboss-web>
       <enable-websockets>true</enable-websockets>
    </jboss-web>
  4. Declare the WebSocket API dependency in your project POM file.

    If you use Maven, you add the following dependency to the project pom.xml file.
    <dependency>
      <groupId>org.jboss.spec.javax.websocket</groupId>
      <artifactId>jboss-websocket-api_1.0_spec</artifactId>
      <version>1.0.0.Final</version>
      <scope>provided</scope>
    </dependency>
    
  5. Configure the JBoss EAP server.

    Configure the http <connector> in the web subsystem of the server configuration file to use the NIO2 protocol.
    1. Start the JBoss EAP server.
    2. Launch the Management CLI using the command for your operating system.
      For Linux:
      EAP_HOME/bin/jboss-cli.sh --connect
      For Windows:
      EAP_HOME\bin\jboss-cli.bat --connect
    3. Enable the NIO2 or the APR connector in the web subsystem of the JBoss EAP server configuration file.
      • Type the following command to use the non blocking Java NIO2 connector protocol:
        /subsystem=web/connector=http/:write-attribute(name=protocol,value=org.apache.coyote.http11.Http11NioProtocol)
      • If you have installed the Apache Portability Runtime (APR), you can type the following commands to use the Apache Portable Runtime APR native connector protocol:
        /subsystem=web:write-attribute(name=native,value=true)
        /subsystem=web/connector=http/:write-attribute(name=protocol,value=org.apache.coyote.http11.Http11AprProtocol)
      For either command, you should see the following result:
      {
          "outcome" => "success",
          "response-headers" => {
              "operation-requires-reload" => true,
              "process-state" => "reload-required"
          }
      }
    4. Notify the server to reload the configuration.
      :reload
      You should see the following result:
      {
          "outcome" => "success",
          "result" => undefined
      }
      
    5. Review the changes to the JBoss EAP server configuration file. The web subsystem should now contain the following XML for the http <connector>.
      For the NIO2 connector configuration:
      <subsystem xmlns="urn:jboss:domain:web:2.1" default-virtual-server="default-host" native="false">
          <connector name="http" protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="http" socket-binding="http"/>
          <virtual-server name="default-host" enable-welcome-root="true">
          <alias name="localhost"/>
              <alias name="example.com"/>
          </virtual-server>
      </subsystem>
      For the APR connector configuration:
      <subsystem xmlns="urn:jboss:domain:web:2.1" default-virtual-server="default-host" native="true">
          <connector name="http" protocol="org.apache.coyote.http11.Http11AprProtocol" scheme="http" socket-binding="http"/>
          <virtual-server name="default-host" enable-welcome-root="true">
              <alias name="localhost"/>
              <alias name="example.com"/>
          </virtual-server>
      </subsystem>
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.