WebSocket实现在线人数统计

系统在线用户统计
简单说下项目概况,SpringBoot+vue,前后端分离。
需求是,home页面实时显示系统在线人数,根据session和请求ip地址判断用户数量,使用Websocket实现前后端广播,通信。
后端代码如下
pom文件,配置文件,代码(如果打war包在tomcat部署,配置文件注释掉)

 <dependency>
            <!-- websocket -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.websocket</groupId>
            <artifactId>javax.websocket-api</artifactId>
            <version>1.1</version>
            <scope>provided</scope>
        </dependency>

//@Configuration
//@EnableWebSocket
public class WebConfigurers implements WebSocketConfigurer {

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

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {

    }
}

 /**
     * 用来存放每个客户端对应的WebSocket对象
     */
    private static CopyOnWriteArraySet<WebsocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private static Logger log = LoggerFactory.getLogger(WebsocketServer.class);
    private Session session;
    private String ipAddress;
    private static int onlineCount = 0;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        String hostAddress = WebsocketUtil.getRemoteAddress(session).getAddress().getHostAddress();
        log.info("客户端IP:" + hostAddress);
        log.info("来自"+session.getId()+"的连接.......");
        this.ipAddress = hostAddress;
        log.info("客户端IP:" + this.ipAddress);
        webSocketSet.add(this);
    }

    @OnClose
    public void onClose(Session session, @PathParam("key") String classKey) throws IOException {
        //删除
        webSocketSet.remove(this);
        getOnlineCount();
        log.info("当前在线人数:" + onlineCount);
        sendAll(String.valueOf(onlineCount));
        log.info("有一连接关闭");
    }

    @OnMessage
    public void onMessage(Session session, String key) throws IOException {
        getOnlineCount();
        sendAll(String.valueOf(onlineCount));
    }

    public void sendAll(String message) throws IOException {
        log.info("发给所有人!");
        //遍历
        for (WebsocketServer websocketServer: webSocketSet){
            sendMessage(websocketServer,String.valueOf(onlineCount));
        }
    }

    public void sendMessage(WebsocketServer websocketServer, String message) throws IOException{
        websocketServer.session.getAsyncRemote().sendText(message);
    }

    @OnError
    public void onError(Session session, Throwable error, @PathParam("key") String classKey) {
        error.printStackTrace();
        log.info("出错啦");
    }

    private static synchronized Integer getOnlineCount(){
        onlineCount = webSocketSet.size();
        return onlineCount;
    }

前端代码截一部分(前端基本不变,可在网上找到)

function initWebSocket(url) {
  if ("WebSocket" in window) {
    webSocket = new WebSocket(url);//创建socket对象
    console.log(webSocket)
  } else {
    alert("该浏览器不支持websocket!");
  }
  //打开
  webSocket.onopen = function() {
    webSocketOpen();
  };
  //收信
  webSocket.onmessage = function(e) {
    webSocketOnMessage(e);
  };
  //关闭
  webSocket.onclose = function() {
    webSocketClose();
  };
  //连接发生错误的回调方法
  webSocket.onerror = function() {
    console.log("WebSocket连接发生错误");
  };
}

每次系统有新的登录,则全局广播

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冬天豆腐

感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值