SpringBoot webSocket 示例, 实现后台主动向前端推送信息

前提

我们已经有了 HTTP 协议,为什么还需要WebSocket

  • 答案很简单,因为 HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
  • 虽然前端页面轮询也可以,但是轮询的效率低,非常浪费资源(因为必须不停连接,或者 HTTP 连接始终打开。

1.依赖

compile group: 'org.springframework.boot', name: 'spring-boot-starter-websocket', version: '2.2.10.RELEASE'

2.配置文件

package com.dmo.parkingServer.common.config;

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();
    }
}

3.webSocketServer

package com.dmo.parkingServer.manager.websocket;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dmo.parkingServer.common.dto.Constant;
import com.dmo.parkingServer.common.pojo.Reporting;
import com.dmo.parkingServer.common.util.SpringUtil;
import com.dmo.parkingServer.manager.service.ManageReportingService;
import com.dmo.parkingServer.manager.system.biz.UserRoleBiz;
import com.dmo.parkingServer.manager.system.db.Role;
import lombok.extern.slf4j.Slf4j;
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.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/*
 * @Author jt
 * @Description //投诉模块的websocket,实现推送处理功能
 * @ServerEndpoint的路径第一个要是/,不能省略
 * 直接注入Service会报空指针异常,本质原因:spring管理的默认都是单例(singleton),和websocket(多对象)相冲突。
 * @Date 2020/12/2
 **/
@ServerEndpoint("/webSocket/reporting/{userId}")
@Component
@Slf4j
public class ReportingWebSocket {

    private static UserRoleBiz userRoleBiz = (UserRoleBiz) SpringUtil.getBean(UserRoleBiz.class);
    private static ManageReportingService manageReportingService = (ManageReportingService) SpringUtil.getBean(ManageReportingService.class);

    //用来存放每个客户端对应的Session对象。
    public static volatile ConcurrentHashMap<Integer, Session> userSessionMap = new ConcurrentHashMap<>();
    private static volatile ConcurrentHashMap<Session, Integer> sessionUserMap = new ConcurrentHashMap<>();
    private static volatile int onlineCount = 0;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Integer userId) {

        userSessionMap.put(userId, session);
        sessionUserMap.put(session, userId);
        onlineCount++;

        log.info("用户:" + userId + "已连接");
        try {
            session.getBasicRemote().sendText("用户:" + userId + "已经建立连接");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("用户:" + userId + ",网络异常!!!");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        Integer userId = sessionUserMap.get(session);
        sessionUserMap.remove(session);
        userSessionMap.remove(userId);
        onlineCount--;
        log.info("用户" + userId + "退出,当前在线人数为:" + onlineCount);
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param userId 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(Integer userId, Session session) {
        sendMessage(userId);
        log.info("用户" + sessionUserMap.get(session) + " 发来消息:" + userId);
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("用户" + sessionUserMap.get(session) + "错误 ,原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public static void sendMessage(Integer userId) {
    //根据业务实现即可
        
    }
}

4.前端示例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>websocket通讯</title>
</head>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    var socket;

    function openSocket() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
            //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
            //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
            var socketUrl = "http://localhost:50083/parkingServer/webSocket/reporting/" + $("#userId").val();
            socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
            console.log(socketUrl);
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            //打开事件
            socket.onopen = function () {
                console.log("websocket已打开");
                // socket.send("这是来自客户端的消息" + location.href + new Date());
            };
            //获得消息事件
            socket.onmessage = function (msg) {
                console.log(msg.data);
                //发现消息进入    开始处理前端触发逻辑
            };
            //关闭事件
            socket.onclose = function () {
                console.log("websocket已关闭");
            };
            //发生了错误事件
            socket.onerror = function () {
                console.log("websocket发生了错误");
            }
        }
    }

    function sendMessage() {
        if (typeof (WebSocket) == "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            socket.send($("#userId").val());
        }
    }
</script>
<br>
<p>userId:
<div><input id="userId" name="userId" type="text" value="3"></div>
</br>
<div>
    <button onclick="openSocket()">开启socket</button>
</div>
</br>
<div>
    <button onclick="sendMessage()">发送消息</button>
</div>
</body>

</html>

5.业务调用

//审核完推送消息
        ConcurrentHashMap<Integer, Session> userSessionMap = ReportingWebSocket.userSessionMap;
        for (Map.Entry<Integer, Session> integerSessionEntry : userSessionMap.entrySet()) {
            ReportingWebSocket.sendMessage(integerSessionEntry.getKey());
        }

6.使用到的util

package com.dmo.parkingServer.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@SuppressWarnings("unchecked")
@Component
public class SpringUtil implements ApplicationContextAware{

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
    }

    /**
     * getBean
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        if(applicationContext.containsBean(beanName)){
            return applicationContext.getBean(beanName);
        }else{
            return null;
        }
    }

    public static Object getBean(Class requiredType){
        isInjected();
        return applicationContext.getBean(requiredType);
    }

    /**
     * 判断是否注入
     * @return
     */
    public static void isInjected(){
        if(SpringUtil.applicationContext == null){
            throw new RuntimeException("springUtils applicationContext is not injected!");
        }
    }

}

7.本示例功能,前端传递userId,后端根据用户权限,推送数据,在数据发生提交,更新,删除时,遍历在线用户,调用 sendMessage()方法推送数据。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值