Jetty is an open-source web server and servlet container that provides HTTP and WebSocket support. It is widely used in web development projects, especially in Java-based applications. In this article, we will discuss the Jetty 9.4 WebSocket example in detail.
What is WebSocket?
WebSocket is a communication protocol that provides real-time, bi-directional communication between a client and a server. It allows web applications to send and receive data without the need for constant HTTP requests. WebSocket is widely used in web applications that require real-time updates, such as chat applications, online gaming, and financial trading platforms.
What is Jetty 9.4?
Jetty 9.4 is the latest version of the Jetty web server and servlet container. It provides support for the latest Java Servlet API and WebSocket specifications. Jetty 9.4 is a lightweight and scalable web server that is widely used in web development projects.
Jetty 9.4 WebSocket Example
In this example, we will create a simple chat application using Jetty 9.4 WebSocket. The chat application will allow multiple clients to connect to the server and send messages to each other in real-time.
Step 1: Setting up the Project
The first step is to set up a new Maven project in your preferred IDE. You can use any IDE, such as Eclipse, IntelliJ IDEA, or NetBeans. Once you have created the project, you need to add the Jetty WebSocket dependency to your project’s pom.xml file.
- Open the pom.xml file of your project.
- Add the following dependency to the dependencies section of the pom.xml file.
Maven Dependency
<dependency><groupId>org.eclipse.jetty.websocket</groupId><artifactId>javax-websocket-server-impl</artifactId><version>9.4.38.v20210224</version></dependency>
Step 2: Creating the WebSocket Endpoint
The next step is to create the WebSocket endpoint that will handle the communication between the clients and the server. A WebSocket endpoint is a Java class that extends the javax.websocket.Endpoint class and implements the onOpen(), onClose(), onMessage(), and onError() methods.
- Create a new Java class called ChatEndpoint.
- Add the following code to the ChatEndpoint class.
ChatEndpoint.java
package com.example.websocket;import java.io.IOException;import java.util.Collections;import java.util.HashSet;import java.util.Set;import javax.websocket.OnClose;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/chat")public class ChatEndpoint {
private static Set
sessions = Collections.synchronizedSet(new HashSet ()); @OnOpenpublic void onOpen(Session session) {sessions.add(session);System.out.println("New client connected");}
@OnClosepublic void onClose(Session session) {sessions.remove(session);System.out.println("Client disconnected");}
@OnMessagepublic void onMessage(String message, Session session) throws IOException {for (Session s : sessions) {s.getBasicRemote().sendText(message);}}}
In the ChatEndpoint class, we defined a WebSocket endpoint with the @ServerEndpoint(“/chat”) annotation. This endpoint listens for WebSocket connections on the /chat path.
We also implemented the onOpen(), onClose(), and onMessage() methods to handle the WebSocket events. When a client connects to the server, the onOpen() method adds the client’s session to the sessions set. When a client disconnects from the server, the onClose() method removes the client’s session from the sessions set. When a client sends a message to the server, the onMessage() method sends the message to all connected clients.
Step 3: Creating the Client HTML Page
The next step is to create the HTML page that will run the chat application on the client-side. The HTML page will contain a WebSocket connection to the server and a form to send messages.
- Create a new HTML file called index.html.
- Add the following code to the index.html file.
index.html
<!DOCTYPE html><html><head><title>Chat Application</title><script type="text/javascript">var webSocket = new WebSocket("ws://" + location.hostname + ":8080/chat");webSocket.onmessage = function(event) {var chatHistory = document.getElementById("chat-history");chatHistory.innerHTML += event.data + "<br>";};function sendMessage() {var messageInput = document.getElementById("message-input");var message = messageInput.value;webSocket.send(message);messageInput.value = "";}</script></head><body><h1>Chat Application</h1><div id="chat-history"></div><form onsubmit="sendMessage(); return false;"><input type="text" id="message-input" placeholder="Type your message here"><button type="submit">Send</button></form></body></html>
In the index.html file, we defined a WebSocket connection to the server using the WebSocket constructor. We also defined a function called sendMessage() that sends the input message to the server when the form is submitted. When the server sends a message to the client, the onmessage() event handler appends the message to the chat history div.
Step 4: Running the Application
The final step is to run the application on the Jetty web server.
- Open a terminal or command prompt.
- Navigate to the project directory.
- Run the following command to start the Jetty web server.
Command
mvn jetty:run
Once the Jetty web server has started, open a web browser and navigate to http://localhost:8080/index.html. You should see the chat application running in the browser.
Conclusion
In this article, we discussed the Jetty 9.4 WebSocket example in detail. We created a simple chat application using Jetty 9.4 WebSocket and explained each step of the process. WebSocket is a powerful communication protocol that allows web applications to provide real-time updates to users. Jetty 9.4 is a lightweight and scalable web server that is widely used in web development projects.
FAQ
What is Jetty?
Jetty is an open-source web server and servlet container that provides HTTP and WebSocket support. It is widely used in web development projects, especially in Java-based applications.
What is WebSocket?
WebSocket is a communication protocol that provides real-time, bi-directional communication between a client and a server. It allows web applications to send and receive data without the need for constant HTTP requests. WebSocket is widely used in web applications that require real-time updates, such as chat applications, online gaming, and financial trading platforms.
What is the latest version of Jetty?
The latest version of Jetty is Jetty 9.4.