springboot整合WebSocket实现后台向前端的消息推送

1、配置pom.xml

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

2、编写websocket配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;.
@Configuration
public class WebSocketConfig {

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

    @Bean
    public WebSocketEndpointConfigure newConfigure() {
        return new WebSocketEndpointConfigure();
    }

}

3、编写 WebSocketEndpoint配置类

import javax.websocket.server.ServerEndpointConfig;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class WebSocketEndpointConfigure extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    private static volatile BeanFactory context;

    @Override
    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return context.getBean(clazz);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        WebSocketEndpointConfigure.context = applicationContext;
    }
}
4、编写WebSocketServer
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint(value = "/webSocket/{userId}", configurator = WebSocketEndpointConfigure.class)
public class WebSocketServer {
    // ConcurrentHashMap用来存放每个客户端对应的WebSocketServer对象。
    private static ConcurrentHashMap<String,Session> webSocketSet = new ConcurrentHashMap<String, Session>();
    private Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("userId") String userId) {
        webSocketSet.put(userId,session);
        //相关业务处理,根据拿到的用户ID判断其为那种角色,根据角色ID去查询是否有需要推送给该角色的消息,有则推送
        List<String> totalPushMsgs = new ArrayList<String>();
        totalPushMsgs.add("欢迎您:"+ userId);
        if(totalPushMsgs != null && !totalPushMsgs.isEmpty()) {
            totalPushMsgs.forEach(e -> sendMessage(userId,e));
        }
    }

    public void sendMessage(String userId,String message) {
        try {
            Session currentSession = webSocketSet.get(userId);
            if(currentSession != null){
                currentSession.getBasicRemote().sendText(message);
            }
            log.info("推送消息成功,消息为:" + message);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    /**
     * 自定义消息
     */
    public static void sendInfo(String userId,String message) throws IOException {
        Session currentSession = webSocketSet.get(userId);
        if(currentSession != null){
            currentSession.getBasicRemote().sendText(message);
        }
    }

    /**
     * 用户退出时,连接关闭调用的方法
     */
    public static void onCloseConection(String userId) {
        webSocketSet.remove(userId); // 从set中删除
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("一个客户端关闭连接");
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {

    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("websocket出现错误");
    }
}

5、编写前端代码

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
    var websocket = null;
 
    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8761/webSocket/111");
    }
    else{
        alert('Not support websocket')
    }
 
    //连接发生错误的回调方法
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };
 
    //连接成功建立的回调方法
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }
 
    //接收到消息的回调方法
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }
  
    //连接关闭的回调方法
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }
 
    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function(){
        websocket.close();
    }
 
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }
 
    //关闭连接
    function closeWebSocket(){
        websocket.close();
    }
  
    //发送消息
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>

6、java后台只需要

WebSocketServer.sendInfo(userId,"我是后台消息");

消息会发送到 websocket.onmessage方法上

猜你喜欢

转载自blog.csdn.net/xiaohanshasha/article/details/86628208