WebSocket is a protocol for full-duplex communication between the client and the server. It allows the server to push messages to the client without the client requesting it. Spring WebSocket is an extension of the Spring framework that allows real-time, bidirectional communication between the client and the server. In this article, we will explore Spring WebSocket Example and its implementation.
What is Spring WebSocket?
Spring WebSocket is a sub-project of Spring Framework, which provides support for WebSocket-based, two-way communication between the client and the server. It allows developers to create real-time, bidirectional, and event-driven communication over the web. Spring WebSocket is built on top of WebSocket API, which is a standard protocol for full-duplex communication between the client and the server.
Why Use Spring WebSocket?
Spring WebSocket provides the following benefits:
- Real-time Communication: Spring WebSocket allows real-time, bidirectional communication between the client and the server.
- Efficient Communication: Unlike traditional HTTP-based communication, WebSocket-based communication is more efficient and requires lesser overhead.
- Event-driven Communication: Spring WebSocket allows event-driven communication, which means that the server can push messages to the client without the client requesting it.
- Built-in Security: Spring WebSocket provides built-in security features, such as authentication and authorization, to ensure secure communication between the client and the server.
Spring WebSocket Example
Let’s take a look at a simple Spring WebSocket example. In this example, we will create a chat application that allows real-time communication between the client and the server.
Prerequisites
Before we start, make sure that you have the following tools installed:
- Java Development Kit (JDK) version 8 or higher
- Apache Maven
Step 1: Create a Maven Project
The first step is to create a Maven project. Open a terminal or command prompt and run the following command:
mvn archetype:generate -DgroupId=com.example -DartifactId=websocket-demo -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This will create a new directory called “websocket-demo” with the following structure:
- websocket-demo
- src
- main
- java
- resources
- test
- java
- resources
- pom.xml
Step 2: Add Spring WebSocket Dependency
The next step is to add the Spring WebSocket dependency to the project’s pom.xml file. Open the pom.xml file and add the following dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
This will add the Spring WebSocket dependency to the project.
Step 3: Create a WebSocket Configuration Class
The next step is to create a WebSocket configuration class. Create a new Java class called “WebSocketConfig” in the “com.example” package and add the following code:
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), “/chat”);
}
}
This class configures the WebSocket handler for the chat application. We register a new WebSocketHandler with the “/chat” endpoint.
Step 4: Create a WebSocket Handler Class
The next step is to create a WebSocket handler class. Create a new Java class called “WebSocketHandler” in the “com.example” package and add the following code:
public class WebSocketHandler extends TextWebSocketHandler {
private List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession webSocketSession : sessions) {
webSocketSession.sendMessage(message);
}
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}
}
This class handles WebSocket messages and maintains a list of connected WebSocket sessions. When a message is received, it sends the message to all connected sessions. When a new session is established, it adds the session to the list of connected sessions.
Step 5: Create a Chat HTML Page
The final step is to create a chat HTML page that allows users to send and receive messages. Create a new HTML file called “chat.html” in the “src/main/resources/static” directory and add the following code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Spring WebSocket Chat</title>
<script src=”/webjars/jquery/jquery.min.js”></script>
<script src=”/webjars/sockjs-client/sockjs.min.js”></script>
<script src=”/webjars/stomp-websocket/stomp.min.js”></script>
<script>
var stompClient = null;
function connect() {
var socket = new SockJS(‘/chat’);
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
stompClient.subscribe(‘/topic/messages’, function (message) {
showMessage(JSON.parse(message.body).content);
});
});
}
function sendMessage() {
var message = document.getElementById(‘message’).value;
stompClient.send(“/app/chat”, {}, JSON.stringify({‘content’: message}));
}
function showMessage(message) {
var p = document.createElement(‘p’);
p.appendChild(document.createTextNode(message));
document.getElementById(‘messages’).appendChild(p);
}
connect();
</script>
</head>
<body>
<div id=”messages”></div>
<form>
<input type=”text” id=”message” />
<button type=”button” onclick=”sendMessage()”>Send</button>
</form>
</body>
</html>
This HTML file creates a chat application that connects to the “/chat” endpoint and sends and receives messages using STOMP.
Step 6: Run the Application
The final step is to run the application. Open a terminal or command prompt and navigate to the project’s directory. Run the following command:
mvn spring-boot:run
This will start the Spring Boot application. Open a web browser and navigate to “http://localhost:8080/chat.html”. You should see a chat application that allows real-time communication between the client and the server.
Conclusion
In this article, we explored Spring WebSocket Example and its implementation. We learned how to create a chat application that allows real-time communication between the client and the server using Spring WebSocket. Spring WebSocket provides real-time, bidirectional, and event-driven communication over the web, making it an ideal choice for applications that require real-time communication.
FAQs
What is WebSocket?
WebSocket is a protocol for full-duplex communication between the client and the server. It allows the server to push messages to the client without the client requesting it.
What is Spring WebSocket?
Spring WebSocket is a sub-project of Spring Framework, which provides support for WebSocket-based, two-way communication between the client and the server.
What are the benefits of using Spring WebSocket?
Spring WebSocket provides the following benefits:
- Real-time Communication
- Efficient Communication
- Event-driven Communication
- Built-in Security
What is STOMP?
STOMP (Simple Text Oriented Messaging Protocol) is a messaging protocol that defines the format and rules for communicating over WebSocket. It provides a simple, text-based interface for messaging.