Springboot integrates websocket to push information to the front in the background

Program description DD 2021-06-18 10:41:49
springboot integrates websocket push information


In a project development , Using the Netty Network application framework , as well as MQTT Send and receive message data , This requires the background to actively push the obtained messages to the front end , So it was used MQTT, It is hereby recorded that .

One 、 What is? websocket?

WebSocket The protocol is based on TCP A new network protocol . It realizes full duplex communication between client and server , I've learned computer network , Since it's full duplex , It means that the server can actively send information to the client . This is in line with our push technology or the function of multi person online chat .

blockbuster !Spring Boot 2.5.0 Hot release , Can you still learn to move ?

Why not use HTTP What about the agreement? ? This is because HTTP It's simplex communication , Communication can only be initiated by the client , The client asks for , The server handles , This is too much trouble . therefore websocket emerge as the times require .

Dry goods : In depth analysis of MySQL Index and SQL Tuning practice

Let's start using Springboot Start integrating . The following cases are all tested successfully on my own computer , You can modify it according to your own functions . My project structure is as follows :

What is a data Lake ? Why data lake ? How to build a lake ? how ETL?

Two 、 Use steps

1. Add dependency

Maven rely on :


2. Enable Springboot Yes WebSocket Support for

Enable WebSocket The support is also very simple , A few lines of code :

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
* @ Auther: Ma Chaowei
* @ Date: 2020/06/16/14:35
* @ Description: Turn on WebSocket Support
public class WebSocketConfig {
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();

3. The core configuration :WebSocketServer

because WebSocket It is similar to the form of client server ( use ws agreement ), So here WebSocketServer In fact, it's equivalent to a ws Agreed Controller

  • @ ServerEndpoint An annotation is a class level annotation , Its main function is to define the current class as a websocket Server side , The value of the annotation will be used to monitor the terminal access of the user connection URL Address , The client can use this URL To connect to WebSocket Server side
  • Create a new one ConcurrentHashMap webSocketMap Used to receive the current userId Of WebSocket, It's convenient to pass between userId Push messages .

Here is the specific business code :

package cc.mrbird.febs.external.webScoket;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;
* Created with IntelliJ IDEA.
* @ Auther: Ma Chaowei
* @ Date: 2020/06/16/14:35
* @ Description:
* @ ServerEndpoint An annotation is a class level annotation , Its main function is to define the current class as a websocket Server side ,
* The value of the annotation will be used to monitor the terminal access of the user connection URL Address , The client can use this URL To connect to WebSocket Server side
public class WebSocketServer {
// Static variables , To record the current number of online connections . It should be designed to be thread safe .
private static int onlineCount = 0;
//concurrent Thread safety of package Set, Used to store the corresponding MyWebSocket object .
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
// A connection session with a client , It is needed to send data to the client
private Session session;
// receive sid
private String sid = "";
* Connection establishment method called successfully
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); // Join in set in
this.sid = sid;
addOnlineCount(); // The online number 1
try {
log.info(" There's a new window to start listening :" + sid + ", The current online population is :" + getOnlineCount());
} catch (IOException e) {
log.error("websocket IO Exception");
* Connection closes the called method
public void onClose() {
webSocketSet.remove(this); // from set Delete in
subOnlineCount(); // The online number minus 1
// When disconnected , Update motherboard occupancy to release
log.info(" Released sid by :"+sid);
// Here you are When released , Business to deal with
log.info(" There is a connection closed ! The current online population is " + getOnlineCount());
* Method called upon receipt of a client message
* @ Param message The message sent by the client
public void onMessage(String message, Session session) {
log.info(" Received from window " + sid + " Information about :" + message);
// Group-sent message
for (WebSocketServer item : webSocketSet) {
try {
} catch (IOException e) {
* @ Param session
* @ Param error
public void onError(Session session, Throwable error) {
log.error(" An error occurred ");
* Realize server active push
public void sendMessage(String message) throws IOException {
* Group custom messages
public static void sendInfo(String message, @PathParam("sid") String sid) throws IOException {
log.info(" Push message to window " + sid + ", Push content :" + message);
for (WebSocketServer item : webSocketSet) {
try {
// You can only push this one here sid Of , by null Then all push
if (sid == null) {
// item.sendMessage(message);
} else if (item.sid.equals(sid)) {
} catch (IOException e) {
public static synchronized int getOnlineCount() {
return onlineCount;
public static synchronized void addOnlineCount() {
public static synchronized void subOnlineCount() {
public static CopyOnWriteArraySet<WebSocketServer> getWebSocketSet() {
return webSocketSet;

4. test Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
* Created with IntelliJ IDEA.
* @ Auther: Ma Chaowei
* @ Date: 2020/06/16/14:38
* @ Description:
public class SystemController {
// Page request
public ModelAndView socket(@PathVariable String userId) {
ModelAndView mav = new ModelAndView("/socket1");
mav.addObject("userId", userId);
return mav;
// Push data interface
public Map pushToWeb(@PathVariable String cid, String message) {
Map<String,Object> result = new HashMap<>();
try {
WebSocketServer.sendInfo(message, cid);
result.put("code", cid);
result.put("msg", message);
} catch (IOException e) {
return result;

5. The test page index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>Java Back end WebSocket Of Tomcat Realization </title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<div id="main" style="width: 1200px;height:800px;"></div>
Welcome<br/><input id="text" type="text" />
<button onclick="send()"> Send a message </button>
<button onclick="closeWebSocket()"> close WebSocket Connect </button>
<div id="message"></div>
<script type="text/javascript">
var websocket = null;
// Determine whether the current browser supports it WebSocket
if('WebSocket' in window) {
// Change your address to
websocket = new WebSocket("ws://");
} else {
alert(' Current browser Not support websocket')
// Callback method for connection error
websocket.onerror = function() {
setMessageInnerHTML("WebSocket Connection error ");
// Callback method for successful connection establishment
websocket.onopen = function() {
setMessageInnerHTML("WebSocket Successful connection ");
var U01data, Uidata, Usdata
// The callback method that receives the message
websocket.onmessage = function(event) {
// Call-back method for connection closure
websocket.onclose = function() {
setMessageInnerHTML("WebSocket Connection is closed ");
// Listen for window closing events , When the window closes , Active close websocket Connect , Prevent Windows from closing before the connection has been disconnected ,server The end throws an exception .
window.onbeforeunload = function() {
// Displays the message on the web page
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
// close WebSocket Connect
function closeWebSocket() {
// Send a message
function send() {
var message = document.getElementById('text').value;
websocket.send('{"msg":"' + message + '"}');
setMessageInnerHTML(message + "&#13;");

6. Result display

backstage : If there is a connection request

The front desk shows :

Regular expressions are commonly used ( Quick reference manual )


I have a problem in the middle , That is to say WebSocket Start up prior to spring Containers , Which leads to WebSocketServer Call business in Service Null pointer exception will be reported

So you need to be in WebSocketServer Will be used in the service Give static initialization : As shown in the figure :

Spring Security 5.5 Release , Formal dress OAuth2.0 The fifth mode of Authorization

You also need to do the following configuration :

520, Send a wave of high quality Java Classic books ! There must be something you want that hasn't started yet !

This article is from WeChat official account. - Program the ape DD(didispace)

The source and reprint of the original text are detailed in the text , If there is any infringement , Please contact the [email protected] Delete .

Original publication time : 2021-05-23

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

本文为[Program description DD]所创,转载请带上原文链接,感谢

  1. HTML + CSS + JavaScript to achieve cool Fireworks (cloud like particle text 3D opening)
  2. HTML + CSS + JavaScript realizes 520 advertising love tree (including music), which is necessary for programmers to express themselves
  3. Solve the problem of Web front-end deployment server (it can be deployed online without a server)
  4. HTML + CSS + JS make wedding countdown web page template (520 / Tanabata Valentine's Day / programmer advertisement)
  5. What else can driverless minibus do besides "Park connection"?
  6. Cloud native leads the era of all cloud development
  7. NRM mirror source management tool
  8. Bring it to you, flex Jiugong
  9. Lolstyle UI component development practice (II) -- button group component
  10. Deconstruction assignment in ES6
  11. Luo 2 peerless Tang clan was officially launched. The official gave a key point, and the broadcast time was implied
  12. 20初识前端HTML(1)
  13. 当新零售遇上 Serverless
  14. 20 initial knowledge of front-end HTML (1)
  15. When new retail meets serverless
  16. [golang] - go into go language lesson 5 type conversion
  17. [golang] - go into go language lesson 6 conditional expression
  18. HTML5(八)——SVG 之 path 详解
  19. HTML5 (8) -- detailed explanation of SVG path
  20. 需要开通VIP以后页面内容才能复制怎么办?控制台禁用javascript即可
  21. Web前端|CSS入门教程(超详细的CSS使用讲解,适合前端初学者)
  22. 实践积累 —— 用Vue3简单写一个单行横向滚动组件
  23. Serverless 全能选手,再下一城
  24. What if you need to open a VIP to copy the page content? Just disable JavaScript on the console
  25. Web front end | CSS introductory tutorial (super detailed CSS explanation, suitable for front-end beginners)
  26. Practice accumulation - write a single line horizontal scroll component simply with vue3
  27. Dili Reba is thin again. She looks elegant and high in a strapless hollow skirt, and her "palm waist" is beautiful to a new height
  28. Serverless all-round player, next city
  29. The difference between MySQL semi synchronous replication and lossless semi synchronous replication
  30. Vue表单设计器的终极解决方案
  31. The ultimate solution for Vue form designer
  32. Nginx从理论到实践超详细笔记
  33. Yu Shuxin's red backless swimsuit is split to the waist and tail, with a concave convex figure and excessive color matching, and his face is white to dazzling
  34. Nginx ultra detailed notes from theory to practice
  35. 【动画消消乐|CSS】086.炫酷水波浪Loading过渡动画
  36. typecho全站启用https
  37. CCTV has another popular employee. The off-site interpretation is very professional, and the appearance ability is no less than that of Wang Bingbing
  38. [animation Xiaole | CSS] 086. Cool water wave loading transition animation
  39. Enable HTTPS in Typecho
  40. 50天用JavaScript完成50个web项目,我学到了什么?
  41. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  42. What have I learned from completing 50 web projects with JavaScript in 50 days?
  43. "My neighbor doesn't grow up" has hit the whole network. There are countless horse music circles, and actor Zhou Xiaochuan has successfully made a circle
  44. 根据JavaScript中原生的XMLHttpRequest实现jQuery的Ajax
  45. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  46. Implement the Ajax of jQuery according to the native XMLHttpRequest in JavaScript
  47. 30 + women still wear less T-shirts and jeans. If they wear them like stars, they will lose weight
  48. 数栈技术分享前端篇:TS,看你哪里逃~
  49. Several stack technology sharing front end: TS, see where you escape~
  50. 舍弃Kong和Nginx,Apache APISIX 在趣链科技 BaaS 平台的落地实践
  51. Abandon the landing practice of Kong and nginx, Apache apisik on the baas platform of fun chain technology
  52. 浪迹天涯king教你用elementui做复杂的表格,去处理报表数据(合并表头,合并表体行和列)
  53. 前端HTML两万字图文大总结,快来看看你会多少!【️熬夜整理&建议收藏️】
  54. Wandering around the world king teaches you to use elementui to make complex tables and process report data (merge header, merge table body rows and columns)
  55. 路由刷新数据丢失 - vuex数据读取的问题
  56. Front end HTML 20000 word graphic summary, come and see how much you can【 Stay up late to sort out & suggestions]
  57. Route refresh data loss - vuex data reading problem
  58. Systemctl系统启动Nginx服务脚本
  59. Systemctl system startup nginx service script
  60. sleepless