17.2. Create a WebSocket Application
- 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.xmlfile configured to enable WebSockets. - Project dependencies configured to declare a dependency on the WebSocket API.
- Enable the
NIO2connector in thewebsubsystem of the Red Hat JBoss Enterprise Application Platform server configuration file.
Note
Procedure 17.1. Create the WebSocket Application
Create the JavaScript HTML client.
The following is an example of a WebSocket client. It contains these JavaScript functions:lconnect(): 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 WebSocketonopen,onmessage,onerror, andonclose.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.
<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>Create the WebSocket server endpoint.
You can create a WebSocket server endpoint using either of the following methods.The code example below uses the annotated endpoint approach and handles the following events.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
@ServerEndpointannotation identifies this class as a WebSocket server endpoint and specifies the path. - The
@OnOpenannotation is triggered when the WebSocket connection is opened. - The
@OnMessageannotation is triggered when a message is sent to the WebSocket connection. - The
@OnCloseannotation 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()); } }Configure the jboss-web.xml file.
You must create the<enable-websockets>element in the applicationWEB-INF/jboss-web.xmland set it totrue.<?xml version="1.0" encoding="UTF-8"?> <!--Enable WebSockets --> <jboss-web> <enable-websockets>true</enable-websockets> </jboss-web>
Declare the WebSocket API dependency in your project POM file.
If you use Maven, you add the following dependency to the projectpom.xmlfile.<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>
Configure the JBoss EAP server.
Configure thehttp<connector>in thewebsubsystem of the server configuration file to use theNIO2protocol.- Start the JBoss EAP server.
- Launch the Management CLI using the command for your operating system.For Linux:
For Windows:EAP_HOME/bin/jboss-cli.sh --connectEAP_HOME\bin\jboss-cli.bat --connect - To enable the non blocking Java
NIO2connector protocol in thewebsubsystem of the JBoss EAP server configuration file, type the following command ./subsystem=web/connector=http/:write-attribute(name=protocol,value=org.apache.coyote.http11.Http11NioProtocol)For either command, you should see the following result:{ "outcome" => "success", "response-headers" => { "operation-requires-reload" => true, "process-state" => "reload-required" } } - Notify the server to reload the configuration.
reloadYou should see the following result:{ "outcome" => "success", "result" => undefined } - Review the changes to the JBoss EAP server configuration file. The
websubsystem should now contain the following XML for thehttp<connector>.<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>

Where did the comment section go?
Red Hat's documentation publication system recently went through an upgrade to enable speedier, more mobile-friendly content. We decided to re-evaluate our commenting platform to ensure that it meets your expectations and serves as an optimal feedback mechanism. During this redesign, we invite your input on providing feedback on Red Hat documentation via the discussion platform.