DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Scalable Client-Server Communication With WebSockets and Spring Boot (Part II)
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • Indexed Views in SQL Server: A Production DBA's Complete Guide
  • The Cybersecurity Blind Spot in DevOps Pipelines
  • Understanding Time Series Databases
  • The Agile Paradox
  1. DZone
  2. Coding
  3. Frameworks
  4. Real-Time Communication: Implementing Websockets With Spring Boot

Real-Time Communication: Implementing Websockets With Spring Boot

In this article, we’ll introduce you to the Websockets API and show you how to implement Websockets with the Spring Boot platform.

By 
Thomas Kendall user avatar
Thomas Kendall
·
Apr. 12, 17 · Tutorial
Likes (10)
Comment
Save
Tweet
Share
28.1K Views

Join the DZone community and get the full member experience.

Join For Free

When developing web applications, we sometimes need to push server events down to connected clients. However, HTTP was not designed to allow this. A client opens a connection to a server and requests data. A server does not open a connection to a client and push data.

To get around this limitation, a polling pattern was established where web pages would intermittently poll the server for any new events. This pattern was not ideal as it added HTTP overhead, was only as fast as the polling rate and caused unnecessary load on the server.

Luckily, with the emergence of HTML5 came the WebSocket. The WebSocket protocol enables interaction between a browser and a web server with lower overheads. In this blog, we’ll introduce the Websockets API and show how to implement Websockets with Spring Boot.

HTML5 to the Rescue!

WebSockets provide full-duplex communication over a single connection between the browser and the server. It does not have the overhead of HTTP and allows the server to push messages to the client in real-time.

The WebSocket API is actually quite simple. Create a WebSocket object, attach event listeners, and send messages.

Here is an example:

var socket = new WebSocket('ws://' + window.location.host + '/my-websocket-endpoint');

// Add an event listener for when a connection is open
socket.onopen = function() {
  console.log('WebSocket connection opened. Ready to send messages.');

  // Send a message to the server
  socket.send('Hello, from WebSocket client!');
};

// Add an event listener for when a message is received from the server
socket.onmessage = function(message) {
  console.log('Message received from server: ' + message);
};

Spring Boot

Spring has excellent support for interfacing with WebSockets.

First, we need to create a class that extends the Spring class TextWebSocketHandler .

public class MyMessageHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        // The WebSocket has been closed
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // The WebSocket has been opened
        // I might save this session object so that I can send messages to it outside of this method

        // Let's send the first message
        session.sendMessage(new TextMessage("You are now connected to the server. This is the first message."));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage textMessage) throws Exception {
        // A message has been received
        System.out.println("Message received: " + textMessage.getPayload());
    }
}

Next, we need to configure our WebSocket endpoint.

@Configuration
@EnableWebSocket
public class WebsocketConfig implements WebSocketConfigurer {

    @Bean
    public WebSocketHandler myMessageHandler() {
        return new MyMessageHandler();
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myMessageHandler(), "/my-websocket-endpoint");
    }

}

Since the WebSockets API is pure JavaScript, you should be able to use it in most front-end frameworks. This includes Angular, as you can include JavaScript right in there with the TypeScript.

Final Thoughts

Pretty simple, and it solves a big headache in regards to the transfer of data between the server and client simultaneously. Spring Boot makes it even easier.

Want to see Websockets in action? At Keyhole, we have built an open source tool, Trouble Maker, that injects failures into our platform so that we can exercise and test the recovery mechanisms that make the platform resilient. Trouble Maker has an Angular front-end and utilizes WebSockets for some real-time communication. Check out the Github Repo to try it in action.

Spring Framework WebSocket Spring Boot

Published at DZone with permission of Thomas Kendall, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Scalable Client-Server Communication With WebSockets and Spring Boot (Part II)
  • Full-Duplex Scalable Client-Server Communication with WebSockets and Spring Boot (Part I)
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: