springBoot Implements Web Socket Message Push

First, enter the following code in the page:

First: Front-end code

var websocket = null;
if('Websocket' in window) {
    websocket = new WebSocket('ws://Here is the address of the page you want to implement.  
    alert('This browser does not support websocket');
websocket.onopen = function (event) {
    console.log('Establish connection');
websocket.onclose = function (event) {
    // body...
    console.log('Connection closure');
websocket.onmessage = function(event){
    console.log('Receive message:' + event.data);
websocket.onerror = function(){
    alert('websocket Communication Error');
window.onbeforeunload = function(){

Second: Introducing dependencies into project maven:


2.1 Create a new configuration class

public class WebSocketConfig {
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();

Three. Use

public class WebSocket {
    private Session session;
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
    public void onOpen(Session session){
        this.session = session;
        log.info("[websocket There are new connections, total:{}",webSockets.size());

    public void onClose(){
        log.info("[websocket Message) Connection disconnected, total:{}",webSockets.size());

    public void onMessage(String message){
        log.info("[websocket Message) Receive a message from the client{}",message);

    public void sendMessage(String message){
        for (WebSocket webSocket : webSockets){
            log.info("[websocket Message) Broadcast Message message{}",message);
            try {
            } catch (IOException e) {

3.1 When you log on to the page of the script code you just generated, it appears as follows; it is the connection that is established in the corresponding front-end script.

3.2 Generates a test push message class as follows

public class TestController {
    private WebSocket webSocket;
    public String tests(){
        webSocket.sendMessage("This is the test message push function");
        return "this is test";

3.3 After login to this page

This is a reminder of the receiving page.

When information can be sent to the front page, it is equivalent to any way you want to remind yourself, for example, pop up.


Tags: Session Maven Spring

Posted on Wed, 02 Oct 2019 06:01:19 -0400 by arsenalfan14