Springboot integrated WebSockets broadcast message (recommended)

Time:2021-1-15

A brief introduction to WebSockets

RFC 6455, or WebSockets protocol, provides a standardized way to establish a full duplex, two-way communication channel to communicate in the client and server or even a single TCP connection; WebSockets protocol is different from HTTP TCP protocol, but its design purpose is to work through HTTP protocol, which can use port 40 or 443 and reuse the existing firewall rules;


GET /spring-websocket-portfolio/portfolio HTTP/1.1
Host: localhost:8080
Upgrade: websocket 
Connection: Upgrade 
Sec-WebSocket-Key: Uc9l9TMkWGbHFD2qnFHltg==
Sec-WebSocket-Protocol: v10.stomp, v11.stomp
Sec-WebSocket-Version: 13
Origin: http://localhost:8080

The interaction of WebSockets starts with HTTP protocol, and the use of upgrade header turns to the use of upgrade connection; if the status is not 200, the successful response is similar to the following information; if the websocket server is running in nginx, you need to configure websocket upgrade requests; if it is running in the cloud, you need to check whether the relevant cloud supports websocket;


HTTP/1.1 101 Switching Protocols 
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: 1qVdfYHU9hPOl4JYYNXF623Gzn0=
Sec-WebSocket-Protocol: v10.stomp

Comparison of HTTP and websocket

In HTTP and rest, an application needs a lot of URLs; the application and the client use these URLs to interact through the style of request and response; the server will route these requests to the HTTP based URL or method or header for processing;

WebSockets usually have only one link during initialization, and all application messages flow through the same TCP connection, which points to a completely different asynchronous, event driven messaging architecture.

Websocket is a low-end protocol. Unlike HTTP, it does not specify any semantic information in the content of the message, which means that it has no way to route or process the information, unless the client and the server reach an agreement on semantics;

Websocket client and server communicate by using more advanced message protocol (such as stomp) and SEC websocket protocol header based on HTTP handshake request;

3. Precautions

WebSockets can make web pages dynamic and interactive. However, in many cases, Ajax and HTTP streaming or long polling can provide a simple and effective solution. HTTP flow and polling are suitable for infrequent message interaction, while WebSockets are suitable for frequent message interaction. On the Internet, because there is no upgrade header or idle long link is closed, limited by your limited agent, WebSockets interaction may be excluded;

Four websocket configuration and dependency

4.1 dependence

<parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.1.RELEASE</version>
 <relativePath/>
 </parent>
 
 <dependencies>
 <! -- websocket dependency -- >
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-websocket</artifactId>
 </dependency>
 <! -- template engine -- >
 <dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>
 </dependencies>

4.2 configuration

/**
 * @Author lsc
 *@ description < p > websocket configuration class</p>
 * @Date 2019/11/12 22:27
 */
//The stomp protocol is used to transmit messages based on message broker. The controller supports the use of @ message mapping in the @ controller class
@EnableWebSocketMessageBroker
@Configurable
@EnableWebSocket
@Component
public class WebConfig implements WebSocketMessageBrokerConfigurer {

 @Override
 public void registerStompEndpoints(StompEndpointRegistry registry) {
 //Register the endpoint of stomp and map the specified URL
 registry.addEndpoint("/websocket")
 . setallowedorigins ("*") // add allow cross domain access
 . withsockjs(); // specify the sockjs protocol
 }

 @Override
 public void configureMessageBroker(MessageBrokerRegistry registry) {
 //Start the broadcast mode agent and send messages only if the path matches
 registry.enableSimpleBroker("/topic");
 }
}

Five entity classes

5.1 receiving message entity

/**
 * @Author lsc
 *@ description < p > accept client message</p>
 * @Date 2019/11/12 22:42
 */
public class AcceptMessages {

 private String name;

 public String getName() {
 return name;
 }
}

5.2 sending message entity

/**
 * @Author lsc
 *@ description < p > send message to client</p>
 * @Date 2019/11/12 22:42
 */
public class SendMessages {

 private String responseMessage;

 public String getResponseMessage() {
 return responseMessage;
 }

 public void setResponseMessage(String responseMessage) {
 this.responseMessage = responseMessage;
 }
}

Six controllers

/**
 * @Author lsc
 *@ description < p > WebSockets broadcast</p>
 * @Date 2019/11/12 22:49
 */
@Controller
public class WebSocketsController {

 @Message mapping ("/ welcome") // similar to @ requestmapping for client request address mapping
 @SendTo ("/ topic / getresponse") // subscribes to the path in @ SendTo to to send messages
 public SendMessages broadcast(AcceptMessages acceptMessages){
 System.out.println(acceptMessages.getName());
 SendMessages sendMessages = new SendMessages();
 sendMessages.setResponseMessage (knowledge seeker:+ acceptMessages.getName ());
 return sendMessages;
 }

}

7. Front end page

Create a new templates directory under the resource directory WebSockets.html Create a new static directory under the resource directory and continue to create a new JS directory under its subdirectory sockjs.min.js , stomp.min.js ,jquery-3.3.1. min.js ;

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
 <meta charset="UTF-8"/>
 < title > springboot broadcast websocket < / Title >
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ffff0000;">Sorry,not support the WebSocket</h2></noscript>
<div>
 <div>
 < button onclick = "connect();" > connect < / button >
 < button disabled = "disabled" onclick = "disconnect();" > disconnect < / button >
 </div>
 <div>
 < label > enter your name < / label >
 <input type="text"/>
 < button onclick = "sendname();" > send < / button >
 <p></p>
 </div>
</div>
<script th:src="@{js/sockjs.min.js}"></script>
<script th:src="@{js/stomp.min.js}"></script>
<script th:src="@{js/jquery-3.3.1.min.js}"></script>
<script type="text/javascript">
 var stompClient = null;
 //Set up connection
 function setConnected(connected) {
 document.getElementById("connect").disabled = connected;
 document.getElementById("disconnect").disabled = !connected;
 document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';
 $("#response").html();
 }
 //Connection
 function connect() {
 //The endpoint is called websocket
 var socket = new SockJS('/websocket');
 //Protocol using socket
 stompClient = Stomp.over(socket);
 //Connection
 stompClient.connect({}, function (frame) {
 setConnected(true);
 console.log('Connected:' + frame);
 //Define a path in @ SendTo to subscribe messages to the target
 stompClient.subscribe('/topic/getResponse', function (response) {
 showResponse(JSON.parse(response.body).responseMessage);
 })
 });
 }
 function disconnect() {
 if (stompClient != null) {
 stompClient.disconnect();
 }
 setConnected(false);
 console.log('Disconnected');
 }
 function sendName() {
 var name = $('#name').val();
 //Sending messages to the target is defined in the controller @ message mapping
 stompClient.send("/welcome", {}, JSON.stringify({'name': name}));
 }
 function showResponse(message) {
 $("#response").html(message);
 }
</script>
</body>
</html>

Eight views forwarding

When the client request address is localhost:8080/ws Through the spring MVC view forwarder to WebSockets.html ;

/**
 * @Author lsc
 *@ description < p > spingmvc view mapping forwarding</p>
 * @Date 2019/11/12 23:35
 */
@Configurable
@Component
public class WebMvcConfig implements WebMvcConfigurer {

 @Override
 public void addViewControllers(ViewControllerRegistry registry) {
 //Configure view forwarding
 registry.addViewController("/ws").setViewName("/WebSockets");
 }
}

Nine renderings

That is, a browser sends messages, and other connected browsers can also receive messages, that is, broadcast form;

10 references

spring-web

Source code

summary

The above is the spring boot integrated WebSockets broadcast message introduced by Xiaobian. I hope it can help you!

Recommended Today

SDS of redis data structure

SDS(simple dynamic string), simple dynamic string. S and it’s called hacking string. Where hack is stored is the length of the string and the remaining space in SDS. The implementation of SDS insds.cIn the middle. C language string uses a character array of length N + 1 to represent the string of length N, and […]