SpringBoot集成WebSocket实现服务器端主动推送

步骤

  1. maven配置依赖
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
  	</dependency>
  1. 编写WebSocketConfig配置文件,开启websocket支持
/**
 * 开启websocket的支持
 */
@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}
  1. 编写websocket服务类,由于websocket使用的是ws协议,需要使用@ServerEndpoint注解配置请求路径
@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketServer {

    // 统计在线人数
    private static int onlineCount = 0;

    // 用本地线程保存session
    private static ThreadLocal<Session> sessions = new ThreadLocal<Session>();

    // 保存所有连接上的session
    private static Map<String, Session> sessionMap = new ConcurrentHashMap<String, Session>();

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        onlineCount--;
    }

    // 连接
    @OnOpen
    public void onOpen(Session session) {
        sessions.set(session);
        addOnlineCount();
        sessionMap.put(session.getId(), session);
        System.out.println("【" + session.getId() + "】连接上服务器======当前在线人数【" + getOnlineCount() + "】");
    }

    // 关闭连接
    @OnClose
    public void onClose(Session session) {
        subOnlineCount();
        sessionMap.remove(session.getId());
        System.out.println("【" + session.getId() + "】退出了连接======当前在线人数【" + getOnlineCount() + "】");
    }

    // 接收消息 客户端发送过来的消息
    @OnMessage
    public void onMessage(String message, Session session) {

        //message的格式可以包含sessionid, 格式[SID,内容XXX]:1,内容
        System.out.println("【" + session.getId() + "】客户端的发送消息======内容【" + message + "】");
        String[] split = message.split(",");
        String sessionId = split[0];
        Session ss = sessionMap.get(sessionId);
        if (ss != null) {
            String msgTo = "【" + session.getId() + "】发送给【您】的消息:\n【" + split[1] + "】";
            String msgMe = "【我】发送消息给【" + ss.getId() + "】:\n" + split[1];
            sendMsg(ss, msgTo);
            sendMsg(session, msgMe);
        } else {
            for (Session s : sessionMap.values()) {
                if (!s.getId().equals(session.getId())) {
                    sendMsg(s, "【" + session.getId() + "】发送给【您】的广播消息:\n【" + message + "】");
                } else {
                    sendMsg(session, "【我】发送广播消息给大家\n" + message);
                }
            }
        }
    }

// 异常

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("发生异常!");
        throwable.printStackTrace();
    }

    // 发送消息到指定用户的方法
    public synchronized void sendMsg(Session session, String msg) {
        try {
            session.getBasicRemote().sendText(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //广播发送消息
    public synchronized void sendMsgToAll(String msg) {
        try {
            for (Session s : sessionMap.values()) {
                s.getBasicRemote().sendText(msg);
                System.out.println(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  1. 编写Controller类在方法里调用WebSocketServer的实例方法实现主动推送
@Controller
public class IndexController {
  @Autowired
    private WebSocketServer webSocketServer;
    
    @RequestMapping("/send.do")
    public ModelAndView send(){
        ModelAndView modelAndView = new ModelAndView("/send.html");
        webSocketServer.sendMsgToAll(“Hello World”);
        return modelAndView;
    }
}
  1. 前端js创建websocket连接
		 //判断当前浏览器是否支持WebSocket
        if('WebSocket' in window){
            websocket = new WebSocket("ws://127.0.0.1:8080/websocket");
        }
        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);
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章