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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Trending

  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • Why Role-Based Access Control Fails for AI Agents — and How to Fix It With Memory Lineage Engines
  • Designing Frontend Applications for Failure, Not Just Success

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Apr. 12, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
28.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook