Category: javascript
what is WebSocket
Published on 22 Apr 2026
Explanation
WebSocket is a communication protocol
that provides
full-duplex (two-way) communication
between client and server
over a single persistent connection.
Code:
// Example use case: // Chat application where messages are sent instantly without refreshing the page
Explanation
Unlike HTTP, which follows a
request-response model,
WebSocket keeps the connection open so both
client and server can send data
anytime.
Code:
// HTTP: Client -> Request -> Server -> Response (connection closed) // WebSocket: Client <-> Server (connection stays open)
Explanation
WebSockets are commonly used in
real-time applications
such as chat apps, live notifications,
multiplayer
games, stock price updates,
and live dashboards.
Code:
// Example applications: // WhatsApp Web // Live sports score updates // Online trading platforms
Explanation
In Spring Boot, WebSocket support can be
enabled using
@EnableWebSocketMessageBroker
configuration.
Code:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements
WebSocketMessageBrokerConfigurer {
}
Explanation
A WebSocket endpoint allows clients
to connect
to the server using a specific URL.
Code:
@Override
public void registerStompEndpoints(
StompEndpointRegistry registry) {
registry.addEndpoint("/chat").
withSockJS();
}
Explanation
Messages can be sent from server to
client using @SendTo
annotation in Spring Boot.
Code:
@MessageMapping("/send")
@SendTo("/topic/messages")
public String sendMessage(String message) {
return message;
}
Explanation
WebSocket improves performance by
reducing repeated HTTP
requests and enabling
instant communication.
Code:
// Ideal for real-time bidirectional //communication systems