Example of application using:
- Undertow: Servlet container that also provides WebSockets support (JSR 356 implementation).
- Weld: CDI reference implementation.
- Jersey: JAX-RS reference implementation for creating RESTful web services in Java.
- WebSockets: Using the JSR 356 implementation provided by Undertow.
In this example, a message created from the REST API is broadcasted to all WebSocket clients. CDI events are used to send data from the REST API to the WebSocket endpoint.
Follow these steps to build and run this application:
- Open a command line window or terminal.
- Navigate to the root directory of the project, where the
pom.xml
resides. - Compile the project:
mvn clean compile
. - Package the application:
mvn package
. - Change into the
target
directory:cd target
- You should see a file with the following or a similar name:
jersey-websockets-undertow-1.0.jar
. - Execute the JAR:
java -jar jersey-websockets-undertow-1.0.jar
. - A page to test the application will be available at
http://localhost:8080/index.html
. The following endpoints will be available:http://localhost:8080/api/messages
: REST endpoint over HTTP to broadcast a message to the WebSocket clientsws://localhost:8080/push
: WebSocket endpoint to get messages pushed by the server
This application is packed as an uber-jar, making it easy to run, so you don't need to be bothered by installing a servlet container such as Tomcat and then deploy the application on it. Just execute java -jar <jar-file>
and the application will be up and running.
This application uses Undertow, a lighweight Servlet container designed to be fully embeddable. It's used as the default web server in the WildFly Application Server.
The uber-jar is created with the Apache Maven Shade Plugin, that provides the capability to create an executable jar including its dependencies.
Browse to http://localhost:8080/index.html
, type a message in the text field and click Broadcast message to send the message to all WebSocket clients. A new WebSocket connection will be created for each tab you open and the message will be broadcasted to them as well.
Alternatively to the test page, you can broadcast a message with curl:
curl -X POST \
'http://localhost:8080/api/messages' \
-H 'Content-Type: application/json' \
-d '{
"message": "Hello from curl!"
}'
And Postman also can be used to target the REST API. Refer to the src/main/postman
directory for the collection files.