How to work with web socket using react js and spring boot frame works

Udith Shalinda
2 min readNov 19, 2019

--

If you are using maven in spring boot application you have to include below dependencies in pom.xml file

<!-- https://mvnrepository.com/artifact/org.springframework/spring-websocket -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
<!-- RabbitMQ Starter Dependency (Not required if you're using the simple in-memory broker for STOMP) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<!-- Following dependency is required for Full Featured STOMP Broker Relay -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-reactor-netty</artifactId>
</dependency>

If you are using gradle your build.gradle file should have this dependencies.

dependencies {
compile("org.springframework.boot:spring-boot-starter-websocket")
compile("org.webjars:webjars-locator-core")
compile("org.webjars:sockjs-client:1.0.2")
compile("org.webjars:stomp-websocket:2.3.3")
//other dependencies
}

if you want more details about this,please refer the spring-boot documentation on dependencies for the web socket.

Then you have to configure the web socket end points and enables a simple in-memory broker

Controller class looks like this.

@MessageMapping("/sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
return chatMessage;
}

Since I use app prefix in web socket config file this method maps to “app/sendMessage” and then it returns the message content to the path “/topic/public”.In the front end we can subscribe this path (“/topic/public”) and then we will be able to execute any function when it gets a message.

First in front end we should have some dependencies

npm i sockjs-clientnpm i stompjs

import these things on your web socket subscribing file

import SockJS from 'sockjs-client';import Stomp from 'stompjs';

You have to execute below lines and to subscribe that path.

var sock = new SockJS('http://localhost:8102/api/ws');let stompClient = Stomp.over(sock);sock.onopen = function() {  console.log('open');}stompClient.connect({}, function (frame) {   console.log('Connected: ' + frame);   stompClient.subscribe('/topic/public', function (greeting) {     console.log(greeting);
//you can execute any function here
});});

When you want to send the message

stompClient.send("/app/sendMessage", {},"your message here");

Thank you!!

--

--