java WebSocket带参数处理使用

1、webSocket实现代码

复制代码
@Component
public class WebSocketStompConfig {
    //这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket
    // ,如果你使用外置的tomcat就不需要该配置文件
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

@Component
@ServerEndpoint(value = "/webSocket")
@Slf4j
public class WebSocket {
    private static int onlineCount = 0;
    private static ConcurrentHashMap<String, Set<Session>> webSocketMap  = new ConcurrentHashMap<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {

        this.session = session;
        // 获取URL中的参数
        Map<String, List<String>> params = session.getRequestParameterMap();
        List<String> funcTypes = params.get("funcType");

        if (!funcTypes.isEmpty()) {
            // 取出funcType参数的值
            String funcType = funcTypes.get(0);

            if(webSocketMap.containsKey(funcType)){
                webSocketMap.get(funcType).add(session);
            }else{
                Set<Session> sessionSet = new HashSet<>();
                sessionSet.add(session);
                webSocketMap.put(funcType,sessionSet);
            }
        }

        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
    }

    @OnClose
    public void onClose(){
        webSocketMap=new ConcurrentHashMap<>();
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public static void sendMessage(Session session, String message) throws IOException {
        session.getBasicRemote().sendText(message);
    }

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

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

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

    public static void setOnlineCount(int onlineCount) {
        WebSocket.onlineCount = onlineCount;
    }

    public static ConcurrentHashMap<String, Set<Session>> getWebSocketMap() {
        return webSocketMap;
    }

    public static void setWebSocketMap(ConcurrentHashMap<String, Set<Session>> webSocketMap) {
        WebSocket.webSocketMap = webSocketMap;
    }

    public Session getSession() {
        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }

    /**
     * 发送自定义消息
     * */
    public static void sendInfo(String message,String funcType) throws Exception {
        if(webSocketMap.containsKey(funcType)){
            Set<Session> sessionSet = webSocketMap.get(funcType);
            if(sessionSet!=null){
                for (Session session : sessionSet) {
                    if(session.getBasicRemote()!=null){
                        session.getBasicRemote().sendText(message);
                    }
                }
            }
        }else{
            log.error("订阅类型:"+funcType+",不存在!");
            throw new Exception("连接已关闭,请刷新页面后重试");
        }

    }

}

二、java代码调用,往websocker赋数据

复制代码
WebSocket.sendInfo(JSON.toJSONString("sdfasd232"),"3");

三、测试是否连接成功以及推送信息

四、前端代码处理

复制代码
/**
 * 初始化websocket连接
 */
function initWebSocket() {
	var websocket = null;
	if('WebSocket' in window) {
		websocket = new WebSocket("ws://127.0.0.1:8080/webSocket?funcType=3" );
	} else {
		alert("该浏览器不支持websocket!");
	}
	websocket.onopen = function(event) {
		console.log("建立连接");
		websocket.send('Hello WebSockets!');
	}
	websocket.onclose = function(event) {
		console.log('连接关闭')
		reconnect(); //尝试重连websocket
	}
	//建立通信后,监听到后端的数据传递
	websocket.onmessage = function(event) {
		let data = JSON.parse(event.data);
		//业务处理....
		if(data.step == 1){
		   alert(data.msg);
		}
	}
	websocket.onerror = function() {
		// notify.warn("websocket通信发生错误!");
		// initWebSocket()
	}
	window.onbeforeunload = function() {
		websocket.close();
	}
// 重连
function reconnect() {
	console.log("正在重连");
	// 进行重连
	setTimeout(function () {
		initWebSocket();
	}, 1000);
}
相关推荐
CoderYanger10 分钟前
动态规划算法-路径问题:7.礼物的最大价值
开发语言·算法·leetcode·动态规划·1024程序员节
古城小栈10 分钟前
Python 3.14:重塑开发体验的五大技术突破与实践指南
开发语言·python
没有bug.的程序员11 分钟前
GC日志解析:从日志看全流程
java·网络·jvm·spring·日志·gc
WZTTMoon12 分钟前
开发中反复查的 Spring Boot 注解,一次性整理到位
java·spring boot·后端
葡萄城技术团队14 分钟前
Excel 文件到底是怎么坏掉的?深入 OOXML 底层原理讲解修复策略
android·java·excel
小糖学代码18 分钟前
LLM系列:1.python入门:1.初识python
服务器·开发语言·人工智能·python·ai
照物华20 分钟前
MySQL 软删除 (Soft Delete) 与唯一索引 (Unique Constraint) 的冲突与解决
java·mysql
mjhcsp20 分钟前
C++ 后缀自动机(SAM):原理、实现与应用全解析
java·c++·算法
wadesir23 分钟前
掌握 Rust 中的浮点数处理(Rust f64 浮点数与标准库详解)
开发语言·后端·rust
张np34 分钟前
java基础-Vector(向量)
java