Real-Time Communication with WebSocket in Spring Boot

Anjali Chaudhari
3 min readMar 19, 2024

--

In this tutorial, we will explore how to implement real-time communication in a Spring Boot application using WebSocket. WebSocket allows bidirectional, full-duplex communication channels over a single TCP connection, enabling efficient real-time data exchange between clients and servers. With Spring Boot and WebSocket, we’ll set it up so our app can handle these real-time chats smoothly.

1)Install Java Development Kit (JDK), Apache Maven and set up the environment variables.

2) Create a Spring Boot Project
Use Spring Initializr, select “Maven” Project and use the latest stable version of Spring Boot. Add WebSocket dependencies. Then, download the project and open it in your IDE

Or, you can add the following dependencies in your pom.xml file

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

3) Configure WebSocket in Spring Boot

  • Create a configuration class to configure WebSocket in your Spring Boot application and use @EnableWebSocket annotation.
  • Set allowed origins, if necessary, using setAllowedOrigins() method to which allows origins to access resources from a server.

/web-socket/src/main/java/com/example/websocket/config/WebSocketConfig.java

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new WebSocketHandler(), "/websocket").setAllowedOrigins("*");
}
}

4) Handle WebSocket Messages

  • Define methods in your WebSocket handler class to handle various types of WebSocket messages (e.g., text, binary).
  • Use these methods to process incoming messages and send responses back to clients as needed.

/web-socket/src/main/java/com/example/websocket/handler/WebSocketHandler.java

public class WebSocketHandler extends TextWebSocketHandler {

private static Set<WebSocketSession> sessions = new HashSet<>();

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
}

@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
for (WebSocketSession webSocketSession : sessions) {
if (webSocketSession.isOpen()) {
try {
webSocketSession.sendMessage(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

You can use different classes for handling different types of WebSocket messages. TextWebSocketHandler class as it is specifically designed for handling text based WebSocket messages. However, Spring provides other handler classes for handling different types of messages:

  • BinaryWebSocketHandler: used for handling binary messages
  • AbstractWebSocketHandler: a generic class used for handling both binary and text messages

In addition to the handleTextMessage method, you can define other methods in your WebSocket endpoint class to handle various types of WebSocket messages.

For example, you can define methods to handle binary messages, JSON messages, or specific message formats.

5) Implement Client-Side Logic

  • Implement WebSocket client-side logic in your web application using JavaScript.
  • Connect to the WebSocket endpoint using the WebSocket API.
  • Define event handlers to send and receive messages from the server.

/web-socket/src/main/resources/static/index.html

<script>
const socket = new WebSocket("ws://localhost:9090/websocket");

socket.onopen = function(event) {
console.log("WebSocket connection established.");
};

socket.onmessage = function(event) {
const messageData = JSON.parse(event.data);
// Handle incoming message data
console.log("Received message:", messageData);
};

socket.onerror = function(error) {
console.error("WebSocket error: ", error);
};

socket.onclose = function(event) {
console.log("WebSocket connection closed:", event);
};

function sendMessage(message) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(message));
} else {
console.error("WebSocket connection is not open.");
}
}

sendMessage({ sender: "Client", message: "Hello :) !" });
</script>

5) Run the App

On Eclipse IDE:

  • Open pom.xml, go to “Run” > “Run As” > “Maven install”
  • After compiling the project, select “Run” > “Run As” > “Maven build”. A dialog box will appear; inside it, specify spring-boot:run in the Goals field.

On terminal,

  • Navigate to your SpringBoot directory
  • Build the project using mvn clean install
  • Run, mvn spring-boot: run

6) Testing and Debugging

To test the WebSocket communication, you can either use Postman or utilize the console within the browser developer tools. You can then paste the provided JavaScript code into the console to interact with the WebSocket server

Note: Remove the <script>tag while testing on Web Browser

Testing using Postman

Testing using Web Browser Developer Tools

Live Stream Chat - Demo App

I hope you like it :)

--

--