SkillCounty Technology

Messaging feature using React and Spring Boot (part 1 – Introduction to Web Socket and How to use it in REACT)

Hi there,

This is the very beginning of the series “implementing messaging feature using React and Spring Boot”. Many of the new developers who have not worked on websocket till now, ended up spending so much time in research and learning the things from scratch. This series gives you a quick head start, so visit all the parts to make a production ready messaging feature.

Firstly, many of you are thinking, why we need web sockets to implement this?
To answer, this we have to understand methods of request and response protocols,

  1. HTTP (Hyper Text Transfer Protocol) –

    Client or browser request for data using HTTP request and server respond back with data and that’s it. This type of interaction is unidirectional.
HTTP Method

2. SSE (Server Sent Event Protocol):
In this type, client request once and server respond back with stream of HTTP response.

Server sent events

3. Web Sockets:

Web sockets are full duplex means two way communication connection which runs on TCP connection. This is most powerful and fastest way of sending and receiving data through TCP connection in really no time.


Now, how to connect with web socket in REACT?

we need a browser client which will connect to the web socket end point to establish the connection over TCP so that messages can be sent and received over this connection at very high speed. In this series, I am going to use react-stomp library available on NPM.

1. Now, head back to the directory of your project and write,

npm install --save react-stomp

2. Now import this,

import SockJsClient from 'react-stomp';

3. Insert sockJsClient tag

          topics={['channel 1, channel 2']}
          onConnect={() => console.log("Connected!")}
          onDisconnect={() => console.log("Disconnected!")}
          onMessage={(message) => 
                     console.log("message received!")}
          ref={(client) => {
            clientRef = client;

How this SockJsClient props work?

SockJS Client need a end point over which the communication will happen. ( we will create this end point in further parts of the series)

This method will be called when client is successfully connected to the end point.

This method will be called when client disconnected from the end point.

This method will be called with injected message object so that you can use this message accordingly.

This is all about using web socket in REACT, now in upcoming part, we will create end point and learn PUBLISH/SUBSCRIBE model in depth. Stay Tuned!

Leave a comment

Your email address will not be published. Required fields are marked *