Ebooks

Spring WebSocket tutorial

Spring WebSocket tutorial shows how to work with WebSocket in a Spring web application.

Spring is a popular Java application framework for creating enterprise applications.

WebSocket

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. WebSockets are used in highly interactive applications such as games, chats, or stock markets.

TextWebSocketHandler

Spring uses WebSocketHandler to handle WebSocket messages and lifecycle events. TextWebSocketHandler is a WebSocketHandler implementation which processes text messages.

Spring TextWebSocketHandler example

The following application uses TextWebSocketHandler to process text messages via WebSocket.

web.xml
src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           ├───config
│   │           │       MyWebInitializer.java
│   │           │       WebConfig.java
│   │           │       WebSocketConfig.java
│   │           └───handler
│   │                   MyWebSocketHandler.java
│   ├───resources
│   └───webapp
│       │   index.html
│       └───WEB-INF
└───test
    └───java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zetcode</groupId>
    <artifactId>textwebsocketex</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-websocket</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>

        </plugins>
    </build>

</project>

In the pom.xml file we have the following dependencies: spring-webmvc, javax.servlet-api, and spring-websocket.

com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebInitializer extends
        AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return null;
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class, WebSocketConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }
}

MyWebInitializer initializes Spring web application. It provides two configuration classes: WebConfig and WebSocket.

com/zetcode/config/WebConfig.java
package com.zetcode.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
@ComponentScan("com.zetcode")
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

The WebConfig configures the DefaultServlet. In our application, we have a static index.html page, which is processed by the DefaultServlet.

com/zetcode/config/WebSocketConfig.java
package com.zetcode.config;

import com.zetcode.handler.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private MyWebSocketHandler myWebSocketHandler;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(myWebSocketHandler, "/socketHandler");
    }
}

WebSocketConfig configures WebSocket in a Spring web application with @EnableWebSocket.

@Autowired
private MyWebSocketHandler myWebSocketHandler;

We inject our MyWebSocketHandler. It is registered with registerWebSocketHandlers().

com/zetcode/config/MyWebSocketHandler.java
package com.zetcode.handler;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import java.time.LocalTime;

@Component
public class MyWebSocketHandler extends TextWebSocketHandler {

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message)
            throws Exception {

        var clientMessage = message.getPayload();

        if (clientMessage.startsWith("hello") || clientMessage.startsWith("greet")) {
            session.sendMessage(new TextMessage("Hello there!"));
        } else if (clientMessage.startsWith("time")) {
            var currentTime = LocalTime.now();
            session.sendMessage(new TextMessage(currentTime.toString()));
        } else {

            session.sendMessage(new TextMessage("Unknown command"));
        }
    }
}

In the MyWebSocketHandler, we react to the socket messages.

var clientMessage = message.getPayload();

With the getPayLoad() method, we get the client message.

if (clientMessage.startsWith("hello") || clientMessage.startsWith("greet")) {
    session.sendMessage(new TextMessage("Hello there!"));
} else if (clientMessage.startsWith("time")) {
    var currentTime = LocalTime.now();
    session.sendMessage(new TextMessage(currentTime.toString()));
} else {

    session.sendMessage(new TextMessage("Unknown command"));
}

Depending on the message, we send a TextMessage back to the client.

webapp/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home page</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css"
            rel="stylesheet">
</head>
<body>

<div class="ui container">

    <h1>Spring MVC 5 WebSocket</h1>

    <div class="two column grid">
        <div class="row">
            <div class="column">
                <label for="myMessage">Message</label>
            </div>

            <div class="column">
                <div class="ui input">
                    <input type="text" id="myMessage">
                </div>
            </div>
        </div>

        <div class="row">
            <div class="column">
                <label for="output">Response from Server</label>
            </div>

            <div class="column">
                <textarea rows="8" cols="50" id="output" readonly="readonly"></textarea>
            </div>
        </div>

        <div class="row">
            <button class="ui button" onclick="send()">Send</button>
        </div>

    </div>
</div>


<script>
    const socketConn = new WebSocket('ws://localhost:8080/socketHandler');

    function send() {
        const clientMsg = document.getElementById('myMessage');

        if (clientMsg.value) {
            socketConn.send(clientMsg.value);
        }
    }

    socketConn.onmessage = (e) => {

        const output = document.getElementById('output');

        output.value += `${e.data}\n`;
    }
</script>
</body>
</html>

The index.html contains a client interface to the application.

const socketConn = new WebSocket('ws://localhost:8080/socketHandler');

In JavaScript, we create a socket connection.

function send() {
    const clientMsg = document.getElementById('myMessage');

    if (clientMsg.value) {
        socketConn.send(clientMsg.value);
    }
}

Upon button click, we send a text message with send().

socketConn.onmessage = (e) => {

    const output = document.getElementById('output');

    output.value += `${e.data}\n`;
}

The onmessage() event handler is called upon receiving a response. We get the response data and add it to the text area.

In this tutorial, we have created a simple Spring web application with support for WebSocket.

You might also be interested in these related tutorials: Spring @GetMapping tutorial, Spring DefaultServlet tutorial, Introduction to Spring web applications, and Java tutorial.