Search Tutorials

Spring Boot + WebSocket Simple Example | JavaInUse

Spring Boot + WebSocket Simple Example

In this post we develop a Spring Boot Application with WebSocket. In the next chapter we will implement a real time multiuser chat application using Spring Boot + WebSocket + RabbitMQ

What are WebSockets? Need for them?

Following are some of the drawbacks of HTTP due to which they are unsuitable for certain scenarios-
  • Traditional HTTP requests are unidirectional - In traditional client server communication, the client always initiates the request.
  • Half Duplex - User requests for a resource and the server then serves it to the client. The response is only sent after the request. So at a time only a single request occurs.
  • Multiple TCP connections - For each request a new TCPsession is needed to be established and then closed after receiving the response. So without using WebSockets we will have multiple sessions.
  • Heavy - Normal HTTP request and response require exchange of extra data between client and server.
WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection.
  • WebSocket are bi-directional - Using WebSocket either client or server can initiate sending a message.
  • WebSocket are Full Duplex - The client and server communication is independent of each other.
  • Single TCP connection - The initial connection is using HTTP, then this connection gets upgraded to a socket based connection. This single connection is then used for all the future communication
  • Light - The WebSocket message data exchange is much lighter compared to http.


This tutorial is explained in the below Youtube Video.

Lets Begin-

Maven Project will be as follows-


In the Maven we need the spring boot WebSocket dependency.Maven will be as follows-

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""






Create the SpringBoot Bootstrap class as below-
package com.javainuse.websocket.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

	public static void main(String[] args) {, args);

On the Server end, we recieve the data and reply back to the client. In Spring we can create a customized handler by using either TextWebSocketHandler or BinaryWebSocketHandler. BinaryWebSocketHandler is used to handle more enriched type of data like images. In our case since we need to handle only text so we will use TextWebSocketHandler.
package com.javainuse.websocket.config;


import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class SocketTextHandler extends TextWebSocketHandler {

	public void handleTextMessage(WebSocketSession session, TextMessage message)
			throws InterruptedException, IOException {

		String payload = message.getPayload();
		JSONObject jsonObject = new JSONObject(payload);
		session.sendMessage(new TextMessage("Hi " + jsonObject.get("user") + " how may we help you?"));

In order to tell Spring to forward client requests to the endpoint , we need to register the handler.
package com.javainuse.websocket.config;

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;

public class WebSocketConfig implements WebSocketConfigurer {

	public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
		registry.addHandler(new SocketTextHandler(), "/user");

Next we define the UI part for establishing WebSocket and making the calls-
Define the app.js as follows-
var ws;
function setConnected(connected) {
	$("#connect").prop("disabled", connected);
	$("#disconnect").prop("disabled", !connected);

function connect() {
	ws = new WebSocket('ws://localhost:8080/user');
	ws.onmessage = function(data) {

function disconnect() {
	if (ws != null) {
	console.log("Websocket is in disconnected state");

function sendData() {
	var data = JSON.stringify({
		'user' : $("#user").val()

function helloWorld(message) {
	$("#helloworldmessage").append(" " + message + "");

$(function() {
	$("form").on('submit', function(e) {
	$("#connect").click(function() {
	$("#disconnect").click(function() {
	$("#send").click(function() {

Define the index.html as follows-
<!DOCTYPE html>
    <title>WebSocket Chat Application </title>
    <link href="/bootstrap.min.css" rel="stylesheet">
    <link href="/style.css" rel="stylesheet">
    <script src="/jquery-1.10.2.min.js"></script>
    <script src="/app.js"></script>
<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-8">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">Chat Application:</label>
                    <button id="connect" type="button">Start New Chat</button>
                    <button id="disconnect" type="button" disabled="disabled">End Chat
    <div class="row">
        <div class="col-md-12">
            <table id="chat">
                    <th>Welcome user. Please enter you name</th>
                <tbody id="helloworldmessage">
            <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <textarea id="user" placeholder="Write your message here..." required></textarea>
                <button id="send" type="submit">Send</button>
Start the application- Go to http://localhost:8080 Click on start new chat it opens the WebSocket connection.
Type text in the textbox and click send.
On clicking end chat, the WebSocket connection will be closed.

Download Source Code

Download it -
Spring Boot + WebSocket Hello World Example

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions