WebSocket连接

启动类增加注解并进行Bean注入

@EnableWebSocket

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

pom文件引入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
package com.hwd.campus.security.biz.websocket;

import com.hwd.campus.security.biz.utils.WebsocketUtil;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@Slf4j
@Getter
@ServerEndpoint("/ws/notify/{requireId}/{token}")
@Component
@EqualsAndHashCode
public class NotifyWebsocket {
    private Session session;
    private String token;
    private String requireId;
    private long timeStamp;

    @OnOpen
    public void onOpen(Session session, @PathParam("requireId") String requireId, @PathParam("token") String token) {
        this.session = session;
        this.token = token;
        this.requireId = requireId;
        WebsocketUtil.addNotify(this);
    }

    @OnClose
    public void onClose() {
        WebsocketUtil.delNotify(this);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("requireId") String requireId, @PathParam("token") String token) {
        //处理中心
        log.info("来自客户端" + requireId + "的消息:" + message);
        sendMessage("收到来自客户端" + requireId + "的消息:" + message);
    }

    @OnError
    public void onError(Throwable error) {
        log.error("websocket发生错误" + error);
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        try {
            this.timeStamp = System.currentTimeMillis();
            log.info("发送消息给客户端:" + message);
            this.session.getAsyncRemote().sendText(message);
        } catch (Exception e) {
            log.error("发送消息失败" + e);
            //WebsocketUtil.delNotify(this);
        }
    }
}

工具类

package com.hwd.campus.security.biz.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.hwd.campus.security.biz.websocket.NotifyWebsocket;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CopyOnWriteArraySet;

@Slf4j
public class WebsocketUtil {
    private static final CopyOnWriteArraySet<NotifyWebsocket> NOTIFY_WEBSOCKET_LIST = new CopyOnWriteArraySet<>();

    public static void addNotify(NotifyWebsocket notifyWebsocket) {
        NOTIFY_WEBSOCKET_LIST.add(notifyWebsocket);
        log.info("有新连接加入数据通知服务,服务端当前在线人数为" + NOTIFY_WEBSOCKET_LIST.size());
    }

    public static void delNotify(NotifyWebsocket notifyWebsocket) {
        NOTIFY_WEBSOCKET_LIST.remove(notifyWebsocket);
        log.info("有新连接离开数据通知服务,服务端当前在线人数为" + NOTIFY_WEBSOCKET_LIST.size());
    }

    public static void sendNotifyMsg(String requireId, Object vo) {
        //根据requireId,相同的才发送信息
        if (NOTIFY_WEBSOCKET_LIST.size() == 0) {
            return;
        }
        //发送消息
        for (NotifyWebsocket notify : NOTIFY_WEBSOCKET_LIST) {
            long timeStamp = notify.getTimeStamp();
            long timeMillis = System.currentTimeMillis();
            if (timeStamp > timeMillis) {
                continue;
            }
            if (notify.getRequireId().equals(requireId)) {
                //发送信息
                log.info("已发送数据给" + notify.getRequireId());
                JSONConfig config = new JSONConfig();
                config.setDateFormat(DatePattern.NORM_DATETIME_PATTERN);
                notify.sendMessage(JSONUtil.toJsonStr(vo, config));
            }
        }
    }
}

线上环境可以在nginx配置文件增加如下配置

location /securityWs/ {
        proxy_pass http://192.168.3.152:8400/;
        proxy_redirect off;
        
        proxy_read_timeout 3600s;
        
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
posted @   小侯学编程  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示