Simple integration of websocket technology to achieve message push

Websocket

Introduction

First introduce WebSocket. It is a network communication technology. The biggest feature of this technology is that the server can actively send messages to the client; of course, the client can also actively send messages to the server to achieve message communication between both ends. It belongs to the network. A kind of push message technology.

benefit

Why do we need the websocket technology? Normally, if we want to achieve a function similar to message notification, we have to actively refresh to know if there is a new message? In this case, it seems that our project is very cumbersome and inflexible. If websocket technology is integrated, messages can be refreshed in real time, so that for some real-time messages like article likes, comments, etc., the user experience will be greatly improved.

Not much to say, let’s take a look at the code implementation

Code

pom.xm l
First add the dependency of websocket (this is spring)

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>4.3.7.RELEASE</version>
</dependency>

SpringBoot is as follows

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

Configuration layer

@Component
public class WebSocketConfig {
    
    

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
    
    
    	return new ServerEndpointExporter();
    }
}

Business Layer

@Component
@ServerEndpoint("/webSocket")
public class WebSocket {
    
    

	private Session session;

	//	定义websocket的容器,储存session
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

	//  对应前端写的事件
    @OnOpen
    public void onOpen(Session session){
    
    
        this.session = session;
        webSocketSet.add(this);
        System.out.println("【websocket消息】有新的连接进来了,目标数:"+ webSocketSet.size());
    }

    @OnClose
    public void onClose() {
    
    
        webSocketSet.remove(this);
        System.out.println("【websocket消息】有连接断开了,目标数为:"+ webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
    
    
        System.out.println("【websocket消息】收到客户端发送过来的消息:" + message);
    }

    public void sendMessage(String message){
    
    
        for (WebSocket webSocket : webSocketSet){
    
    
        	System.out.println("【websocket消息】广播消息,message="+ message);
            try {
    
    
                webSocket.session.getBasicRemote().sendText(message);
            } catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }
	
}

controller layer

@Autowired
private WebSocket websocket;
//	在你发送消息(或者实现相关功能的地方)
//  调用websocket的sendMessage方法,将内容代入方法体
websocket.sendMessage("消息内容");

Front page layer

   //	websocket消息通知
   var websocket = null;
   //  判断浏览器是否支持websocket技术
   if('WebSocket' in window) {
       websocket = new WebSocket('ws://127.0.0.1:8080/webSocket');
   }else {
       alert('抱歉,您的浏览器不支持websocket!')
   }

   websocket.onopen = function (event) {
       console.log('建立连接成功')
   }

   websocket.onclose = function (event) {
     console.log('连接已经关闭')
   }

   websocket.onmessage = function (event) {
       console.log('收到消息:' + event.data)
   }

   websocket.onerror = function (event) {
  	   console.log('websocket消息通信发生错误!')
   }
	//  窗口关闭,websocket也就关闭
   window.onbeforeunload = function () {
       websocket.close();
   }

Guess you like

Origin blog.csdn.net/hyx1249273846/article/details/114229732