or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

client-support.mdconfiguration.mdcore-websocket-api.mdhandler-framework.mdindex.mdmessage-types.mdserver-integration.mdsockjs-support.mdstomp-messaging.md
tile.json

tessl/maven-org-springframework--spring-websocket

Spring WebSocket provides comprehensive WebSocket support for Spring applications including both low-level WebSocket API support and higher-level SockJS fallback options

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.springframework/spring-websocket@6.2.x

To install, run

npx @tessl/cli install tessl/maven-org-springframework--spring-websocket@6.2.0

index.mddocs/

Spring WebSocket

Spring WebSocket provides comprehensive WebSocket support for Spring applications, enabling real-time bidirectional communication between web browsers and servers. It includes full support for the standard WebSocket API with Spring-specific abstractions, SockJS transport fallback mechanisms, integration with Spring Security, STOMP protocol support, and seamless integration with Spring's dependency injection and configuration frameworks.

Package Information

  • Package Name: org.springframework:spring-websocket
  • Package Type: maven
  • Language: Java
  • Installation: Add to your Maven pom.xml:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>6.2.8</version>
</dependency>

For Gradle:

implementation 'org.springframework:spring-websocket:6.2.8'

Core Imports

import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.CloseStatus;

Basic Usage

import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("Connection established: " + session.getId());
        session.sendMessage(new TextMessage("Welcome!"));
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("Received: " + payload);
        
        // Echo the message back
        session.sendMessage(new TextMessage("Echo: " + payload));
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("Connection closed: " + session.getId());
    }
}

Architecture

Spring WebSocket is built around several key components:

  • Core WebSocket APIs: WebSocketHandler, WebSocketSession, and message types for handling WebSocket communication
  • Adapter Layer: Integration with different WebSocket implementations (JSR-356, Jetty) through adapters
  • Configuration: Both annotation-based and XML configuration support for registering handlers and endpoints
  • Handler Framework: Extensible handler system with decorators for cross-cutting concerns
  • Messaging Integration: Full STOMP protocol support with Spring messaging framework integration
  • Server Integration: Support for multiple server implementations (Tomcat, Jetty, Undertow, etc.)
  • SockJS Support: Complete fallback solution with 8 different transport types for browsers without WebSocket support

Capabilities

Core WebSocket API

Essential WebSocket interfaces and classes for building WebSocket applications. Provides session management, message handling, and connection lifecycle support.

interface WebSocketHandler {
    void afterConnectionEstablished(WebSocketSession session) throws Exception;
    void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception;
    void handleTransportError(WebSocketSession session, Throwable exception) throws Exception;
    void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception;
    boolean supportsPartialMessages();
}

interface WebSocketSession {
    String getId();
    URI getUri();
    Map<String, Object> getAttributes();
    Principal getPrincipal();
    void sendMessage(WebSocketMessage<?> message) throws IOException;
    boolean isOpen();
    void close() throws IOException;
    void close(CloseStatus status) throws IOException;
}

Core WebSocket API

Message Types

WebSocket message implementations for different data types including text, binary, ping, and pong messages.

class TextMessage extends AbstractWebSocketMessage<String> {
    public TextMessage(CharSequence payload);
    public TextMessage(CharSequence payload, boolean isLast);
    public byte[] asBytes();
}

class BinaryMessage extends AbstractWebSocketMessage<ByteBuffer> {
    public BinaryMessage(ByteBuffer payload);
    public BinaryMessage(ByteBuffer payload, boolean isLast);
    public BinaryMessage(byte[] payload);
}

class PingMessage extends AbstractWebSocketMessage<ByteBuffer> {
    public PingMessage();
    public PingMessage(ByteBuffer payload);
}

class PongMessage extends AbstractWebSocketMessage<ByteBuffer> {
    public PongMessage();
    public PongMessage(ByteBuffer payload);
}

Message Types

Configuration Support

Annotation-based and XML configuration for registering WebSocket handlers and configuring STOMP messaging support.

@EnableWebSocket
@Configuration
class WebSocketConfig implements WebSocketConfigurer {
    void registerWebSocketHandlers(WebSocketHandlerRegistry registry);
}

@EnableWebSocketMessageBroker  
@Configuration
class WebSocketMessageBrokerConfig implements WebSocketMessageBrokerConfigurer {
    void registerStompEndpoints(StompEndpointRegistry registry);
    void configureMessageBroker(MessageBrokerRegistry registry);
}

Configuration

Handler Framework

WebSocket handler implementations and decorators for building robust WebSocket applications with cross-cutting concerns.

abstract class AbstractWebSocketHandler implements WebSocketHandler {
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception;
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception;
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception;
}

class TextWebSocketHandler extends AbstractWebSocketHandler;
class BinaryWebSocketHandler extends AbstractWebSocketHandler;

class WebSocketHandlerDecorator implements WebSocketHandler {
    public WebSocketHandlerDecorator(WebSocketHandler delegate);
    public WebSocketHandler getDelegate();
}

Handler Framework

Client Support

WebSocket client implementations for establishing outbound WebSocket connections with connection management.

interface WebSocketClient {
    ListenableFuture<WebSocketSession> doHandshake(
        WebSocketHandler webSocketHandler, 
        String uriTemplate, 
        Object... uriVariables
    );
    ListenableFuture<WebSocketSession> doHandshake(
        WebSocketHandler webSocketHandler, 
        WebSocketHttpHeaders headers, 
        URI uri
    );
}

class WebSocketConnectionManager extends ConnectionManagerSupport {
    public WebSocketConnectionManager(
        WebSocketClient client, 
        WebSocketHandler webSocketHandler, 
        String uriTemplate, 
        Object... uriVariables
    );
}

Client Support

STOMP Messaging

STOMP (Simple Text Oriented Messaging Protocol) support for higher-level messaging patterns over WebSocket connections.

interface SubProtocolHandler {
    List<String> getSupportedProtocols();
    void handleMessageFromClient(WebSocketSession session, WebSocketMessage<?> message, MessageChannel outputChannel);
    void handleMessageToClient(WebSocketSession session, Message<?> message);
}

class StompSubProtocolHandler implements SubProtocolHandler;

class WebSocketStompClient {
    public WebSocketStompClient(WebSocketClient webSocketClient);
    public void setMessageConverter(MessageConverter messageConverter);
}

STOMP Messaging

Server Integration

Server-side WebSocket support with handshake handling and upgrade strategies for different server implementations.

interface HandshakeHandler {
    boolean doHandshake(
        ServerHttpRequest request, 
        ServerHttpResponse response, 
        WebSocketHandler wsHandler, 
        Map<String, Object> attributes
    ) throws HandshakeFailureException;
}

interface RequestUpgradeStrategy {
    String[] getSupportedVersions();
    void upgrade(
        ServerHttpRequest request, 
        ServerHttpResponse response, 
        String selectedProtocol, 
        List<WebSocketExtension> selectedExtensions, 
        Principal user, 
        WebSocketHandler wsHandler, 
        Map<String, Object> attrs
    ) throws HandshakeFailureException;
}

Server Integration

SockJS Support

SockJS fallback support providing WebSocket-like object in browsers that don't support WebSocket natively, with multiple transport options.

interface SockJsService {
    void handleRequest(
        ServerHttpRequest request, 
        ServerHttpResponse response, 
        String sockJsPath, 
        WebSocketHandler webSocketHandler
    ) throws SockJsException;
}

enum TransportType {
    WEBSOCKET, XHR, XHR_STREAMING, XHR_POLLING, 
    JSONP, JSONP_POLLING, HTML_FILE, EVENT_SOURCE;
}

interface SockJsSession extends WebSocketSession {
    String getId();
    void close() throws IOException;
    void close(CloseStatus status) throws IOException;
}

SockJS Support

Types

final class CloseStatus {
    public static final CloseStatus NORMAL;                      // 1000
    public static final CloseStatus GOING_AWAY;                  // 1001  
    public static final CloseStatus PROTOCOL_ERROR;              // 1002
    public static final CloseStatus NOT_ACCEPTABLE;              // 1003
    public static final CloseStatus NO_STATUS_CODE;              // 1005
    public static final CloseStatus NO_CLOSE_FRAME;              // 1006
    public static final CloseStatus BAD_DATA;                    // 1007
    public static final CloseStatus POLICY_VIOLATION;            // 1008
    public static final CloseStatus TOO_BIG_TO_PROCESS;          // 1009
    public static final CloseStatus REQUIRED_EXTENSION;          // 1010
    public static final CloseStatus SERVER_ERROR;                // 1011
    public static final CloseStatus SERVICE_RESTARTED;           // 1012
    public static final CloseStatus SERVICE_OVERLOAD;            // 1013
    public static final CloseStatus TLS_HANDSHAKE_FAILURE;       // 1015
    public static final CloseStatus SESSION_NOT_RELIABLE;        // 4500
    
    public CloseStatus(int code);
    public CloseStatus(int code, @Nullable String reason);
    public int getCode();
    @Nullable public String getReason();
    public CloseStatus withReason(String reason);
}

class WebSocketExtension {
    public WebSocketExtension(String name);
    public WebSocketExtension(String name, @Nullable Map<String, String> parameters);
    public String getName();
    public Map<String, String> getParameters();
    public static List<WebSocketExtension> parseExtensions(@Nullable String extensions);
}

class WebSocketHttpHeaders extends HttpHeaders {
    public void setSecWebSocketAccept(@Nullable String secWebSocketAccept);
    @Nullable public String getSecWebSocketAccept();
    public List<WebSocketExtension> getSecWebSocketExtensions();
    public void setSecWebSocketExtensions(List<WebSocketExtension> extensions);
    public List<String> getSecWebSocketProtocol();
    public void setSecWebSocketProtocol(String... secWebSocketProtocols);
    public void setSecWebSocketVersion(@Nullable String secWebSocketVersion);
    @Nullable public String getSecWebSocketVersion();
    public void setSecWebSocketKey(@Nullable String secWebSocketKey);
    @Nullable public String getSecWebSocketKey();
}