<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tarun Kishore on Medium]]></title>
        <description><![CDATA[Stories by Tarun Kishore on Medium]]></description>
        <link>https://medium.com/@kishoretarun?source=rss-c31a387dc960------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FC0f9rMm_3kue4z7lWoytw.jpeg</url>
            <title>Stories by Tarun Kishore on Medium</title>
            <link>https://medium.com/@kishoretarun?source=rss-c31a387dc960------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 08:23:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kishoretarun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[WebSockets integration in a Spring Boot application]]></title>
            <link>https://kishoretarun.medium.com/websockets-integration-in-a-spring-boot-application-7e365c015f69?source=rss-c31a387dc960------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e365c015f69</guid>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Tarun Kishore]]></dc:creator>
            <pubDate>Tue, 15 Aug 2023 16:12:16 GMT</pubDate>
            <atom:updated>2023-08-15T16:12:16.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37vCJ798FEAk0Pd7htcrDQ.png" /></figure><p>In this article, we’ll talk about some basics of WebSockets which includes their key features, drawbacks, how WebSocket works, and later we’ll implement some WebSocket APIs in a Spring Boot application.</p><p>In the ever-evolving landscape of web development, user expectations have shifted towards more interactive and real-time experiences. Traditional web applications primarily relied on the request-response model, where a client (usually a web browser) sends an HTTP request to a server, and the server responds with the requested data. However, this approach has limitations regarding achieving true real-time communication and dynamic updates without constant polling.</p><p>This is where WebSockets come into play. WebSockets are a communication protocol that provides full-duplex, bidirectional communication channels over a single, long-lived connection between a client and a server. Unlike the traditional request-response model, where the client initiates each communication, WebSockets allows both the client and server to initiate messages independently. This makes WebSockets ideal for building applications requiring real-time updates, live notifications, online gaming, collaborative tools, financial platforms, and more.</p><h4>Key Features of WebSockets:</h4><ol><li><strong>Full-Duplex Communication</strong>: WebSockets enable simultaneous two-way communication, allowing both the client and server to send and receive messages independently without waiting for a request or response.</li><li><strong>Low Latency</strong>: By establishing a persistent connection, WebSockets significantly reduce the latency compared to traditional polling mechanisms. This is crucial for applications that require instant updates.</li><li><strong>Efficiency</strong>: WebSockets eliminate the overhead of repeatedly establishing new connections for each request, making them more efficient for scenarios that involve frequent communication.</li><li><strong>Real-Time Updates</strong>: WebSockets provide a seamless way to push real-time updates to connected clients, ensuring that users receive live information without having to refresh the page.</li><li><strong>Bi-directional Communication</strong>: WebSockets allow both the client and server to initiate communication, making them well-suited for interactive and collaborative applications.</li><li><strong>Cross-Domain Communication</strong>: With proper configuration, WebSockets can facilitate communication between different domains, enabling cross-origin real-time interactions.</li></ol><h4>Drawbacks of WebSockets:</h4><ol><li><strong>Server resource usage:</strong> WebSocket connections can be resource-intensive for servers that maintain many open connections. This can lead to scaling challenges or increased costs.</li><li><strong>Firewall and proxy issues: </strong>They use a different protocol than HTTP, and some firewalls and proxies may not allow WebSocket traffic to pass through. This can lead to compatibility issues.</li></ol><h4>Protocol Overview</h4><blockquote><em>The protocol consists of an opening handshake followed by basic message framing, layered over TCP.</em></blockquote><blockquote><em>— </em><a href="https://tools.ietf.org/html/rfc6455"><em>RFC 6455 — The WebSocket Protocol</em></a></blockquote><p>WebSockets begin life as a standard HTTP request and response. Within that request-response chain, the client asks to open a WebSocket connection, and the server responds (if it&#39;s able to). If this initial handshake is successful, the client and server have agreed to use the existing TCP/IP connection that was established for the HTTP request as a WebSocket connection. Data can now flow over this connection using a basic framed message protocol. Once both parties acknowledge that the WebSocket connection should be closed, the TCP connection is torn down.</p><h4>Establishing a WebSocket connection:</h4><p>WebSockets do not use the http:// or https:// scheme (because they do not follow the HTTP protocol). Rather, WebSocket URIs use a new scheme ws: (or wss: for a secure WebSocket). The remainder of the URI is the same as an HTTP URI: a host, port, path, and any query parameters.</p><pre>&quot;ws:&quot; &quot;//&quot; host [ &quot;:&quot; port ] path [ &quot;?&quot; query ]<br>&quot;wss:&quot; &quot;//&quot; host [ &quot;:&quot; port ] path [ &quot;?&quot; query ]</pre><p>WebSocket connections can only be established to URIs that follow this scheme. That is if you see a URI with a scheme of ws:// (or wss://), then both the client and the server MUST follow the WebSocket connection protocol to follow the WebSocket specification.</p><p>WebSocket connections are established by <em>upgrading</em> an HTTP request/response pair. A client that supports WebSockets and wants to establish a connection will send an HTTP request that includes a few required headers:</p><ul><li>Connection: Upgrade <br>The Connection header generally controls whether or not the network connection stays open after the current transaction finishes. A common value for this header is keep-alive to make sure the connection is persistent to allow for subsequent requests to the same server. During the WebSocket opening handshake, we set to header toUpgrade, signaling that we want to keep the connection alive and use it for non-HTTP requests.</li><li>Upgrade: websocket<br>The Upgrade header is used by clients to ask the server to switch to one of the listed protocols, in descending preference order. We specify websocket here to signal that the client wants to establish a WebSocket connection.</li><li>Sec-WebSocket-Key: q4xkcO32u266gldTuKaSOw==<br>The Sec-WebSocket-Key is a one-time random value (a nonce) generated by the client. The value is a randomly selected 16-byte value that has been base64-encoded.</li><li>Sec-WebSocket-Version: 13<br>The only accepted version of the WebSocket protocol is 13. Any other version listed in this header is invalid.</li></ul><p>Together, these headers would result in an HTTP GET request from the client to a ws:// URI like in the following example:</p><pre>GET ws://example.com:8181/ HTTP/1.1<br>Host: localhost:8181<br>Connection: Upgrade<br>Pragma: no-cache<br>Cache-Control: no-cache<br>Upgrade: websocket<br>Sec-WebSocket-Version: 13<br>Sec-WebSocket-Key: q4xkcO32u266gldTuKaSOw==</pre><p>Once a client sends the initial request to open a WebSocket connection, it waits for the server’s reply. The reply must have a HTTP 101 Switching Protocols response code. The HTTP 101 Switching Protocolsresponse indicates that the server is switching to the protocol that the client requested in its Upgrade request header. In addition, the server must include HTTP headers that validate that the connection was successfully upgraded:</p><pre>HTTP/1.1 101 Switching Protocols<br>Upgrade: websocket<br>Connection: Upgrade<br>Sec-WebSocket-Accept: fA9dggdnMPU79lJgAE3W4TRnyDM=</pre><ul><li>Connection: Upgrade<br>Confirms that the connection has been upgraded.</li><li>Upgrade: websocket<br>Confirms that the connection has been upgraded.</li><li>Sec-WebSocket-Accept: fA9dggdnMPU79lJgAE3W4TRnyDM=`<br>Sec-WebSocket-Accept is base64 encoded, SHA-1 hashed value. You generate this value by concatenating the clients Sec-WebSocket-Key nonce and the static value 258EAFA5-E914-47DA-95CA-C5AB0DC85B11 defined in RFC 6455. Although the Sec-WebSocket-Key and Sec WebSocket-Accept` seem complicated, they exist so that both the client and the server can know that their counterpart supports WebSockets. Since the WebSocket re-uses the HTTP connection, there are potential security concerns if either side interprets WebSocket data as an HTTP request.</li></ul><p>After the client receives the server response, the WebSocket connection is open to start transmitting data.</p><h4>Creating a WebSocket API in a Spring boot application</h4><p>Since we now know the basics of WebSocket protocol, its benefits, drawback, protocol structure, and definitions, it’s a good time to do some hands-on.</p><p>The Spring Framework provides a WebSocket API that you can use to write client- and server-side applications that handle WebSocket messages.</p><p>Step 1:</p><p>Generate a project file from <a href="https://start.spring.io/">Spring initializr</a>, and add spring-websocket dependency:</p><pre>&lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-websocket&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Step 2:</p><p>Create a WebSocket handler class by implementing WebSocketHandler interface.<br>In the scope of my sample project, I have created a Gamehandler which contains all the overridden methods needed to handle WebSocket requests.</p><p>In the below class, the methods name justifies what that method is going to do, to keep the logic simple I have added just a log line for some methods.</p><p>The handleMessage method is the one which executed when a message comes to a WebSocket connection toed with this WebSocketHandler (GameHandler)</p><p>For the sake of simplicity, I have done some basic stuff in the method, basically, I’m getting the <em>gameId</em> from the request and then replying with 2 messages after an interval of 1 sec using the <em>session.send</em> method which will send the message on the same session where the request was recieved.</p><blockquote>Based on your business logic we can do a lot of stuff here like getting requests in JSON format and then parsing the payload into the required object and then replying back in JSON itself, etc.</blockquote><pre>package com.kishore.poc.config.handler;<br><br>import org.springframework.web.socket.CloseStatus;<br>import org.springframework.web.socket.TextMessage;<br>import org.springframework.web.socket.WebSocketHandler;<br>import org.springframework.web.socket.WebSocketMessage;<br>import org.springframework.web.socket.WebSocketSession;<br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class GameHandler implements WebSocketHandler {<br><br>    @Override<br>    public void afterConnectionEstablished(WebSocketSession session) throws Exception {<br>        log.info(&quot;Connection established on session: {}&quot;, session.getId());<br>    }<br><br>    @Override<br>    public void handleMessage(WebSocketSession session, WebSocketMessage&lt;?&gt; message) throws Exception <br>        String gameId = (String) message.getPayload();<br>        session.sendMessage(new TextMessage(&quot;Started processing game: &quot; + gameId));<br>        Thread.sleep(1000);<br>        session.sendMessage(new TextMessage(&quot;Completed processing game: &quot; + gameId));<br>    }<br><br>    @Override<br>    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {<br>        log.info(&quot;Exception occured: {} on session: {}&quot;, exception.getMessage(), session.getId());<br>    }<br><br>    @Override<br>    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {<br>        log.info(&quot;Connection closed on session: {} with status: {}&quot;, session.getId(), closeStatus.getCode());<br>    }<br><br>    @Override<br>    public boolean supportsPartialMessages() {<br>        return false;<br>    }<br>}</pre><p>Step 3:</p><p>Now we need to point our GameHandler class with an API, for that we need to register that WebSocketHandler (GameHandler) with the WebSocketHandlerRegistry, which is done in the below configuration class.</p><pre>package com.kishore.poc.config;<br><br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br>import org.springframework.web.socket.WebSocketHandler;<br>import org.springframework.web.socket.config.annotation.EnableWebSocket;<br>import org.springframework.web.socket.config.annotation.WebSocketConfigurer;<br>import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;<br>import com.kishore.poc.config.handler.GameHandler;<br><br><br>@Configuration<br>@EnableWebSocket<br>public class WebSocketConfig implements WebSocketConfigurer {<br><br>    @Override<br>    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {<br>        registry.addHandler(gameHandler(), &quot;/game&quot;)<br>                        .setAllowedOrigins(&quot;*&quot;);<br>    }<br><br>    @Bean<br>    public WebSocketHandler gameHandler() {<br>        return new GameHandler();<br>    }<br>}</pre><p>In the above block of code, I’m creating a bean on GameHandler and registering it with WebSocketHandlerRegistry specified URL path which is <em>/game</em><br>So, now when a client is trying to connect to <em>/game</em> then it will redirect all requests to GameHandler.</p><p>Similarly, based on business we can add and configure any number WebSocketHandler by registering them with WebSocketHandlerRegistry.</p><p>Step 4:</p><p>Testing the WebSocket API which we just created, in order to test we can use various tools and extensions present on the internet. I’ll Postman as the WebSocket client:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEvLTI48qsAX5U6dRJRphA.png" /></figure><p>In the above screenshot, we can see that Postman is able to connect with the /game endpoint using ws: URI scheme instead of http: which we use for Rest APIs connection, by adding ws: we are saying that it’ll use WebSocket protocol to connect with the server.</p><p>After that when I send a message it handles the message and replies back 2 times as per the logic we added to the GameHandler class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdnVEnkYLTwBnsIzTmmLjA.png" /></figure><h4>Conclusion</h4><p>In wrapping up our look into WebSockets and how to use them with Spring Boot, we’ve explored a powerful way to make websites more interactive. WebSockets let us exchange information quickly between users and websites, leading to instant updates and engaging experiences. While they offer many benefits, like fast communication and two-way chatting, we also need to handle some challenges, such as managing resources and making sure older systems can still use them. With our hands-on guide to creating a Spring Boot WebSocket, we’ve opened the door to crafting exciting websites that connect people in real-time. As we finish our journey, remember that WebSockets are like a special tool helping us build more dynamic and lively online spaces.</p><p>GitHub repository for the above project: <a href="https://github.com/kishoretarun/websocket-poc">https://github.com/kishoretarun/websocket-poc</a></p><h4>References:</h4><ul><li><a href="https://docs.spring.io/spring-framework/reference/web/websocket.html">WebSockets</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc6455">RFC 6455: The WebSocket Protocol</a></li><li><a href="https://sookocheff.com/post/networking/how-do-websockets-work/">How Do Websockets Work?</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e365c015f69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>