Pig Cloud遇到websocket不能实现同一个用户不同浏览器接受到广播的消息解决方案

自定义SecuritySessionKeyGenerator类,为每个客户端连接建立唯一的key

java 复制代码
package com.pig4cloud.plugin.websocket.custom;

import com.pig4cloud.plugin.websocket.holder.SessionKeyGenerator;
import org.springframework.web.socket.WebSocketSession;

import java.util.UUID;
public class SecuritySessionKeyGenerator implements SessionKeyGenerator {
	@Override
	public Object sessionKey(WebSocketSession webSocketSession) {
		Object user = webSocketSession.getAttributes().get("USER_KEY_ATTR_NAME");
		// 添加随机后缀使每个连接键唯一
		return user != null ? user + "-" + UUID.randomUUID().toString() : null;
	}
}

重写WebSocketSessionHolder类方法

java 复制代码
package com.pig4cloud.plugin.websocket.holder;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import org.springframework.web.socket.WebSocketSession;

public final class WebSocketSessionHolder {
	// 仅修改这一行:将Value改为Set类型
	private static final Map<String, Set<WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap<>();

	private WebSocketSessionHolder() {
	}

	public static void addSession(Object sessionKey, WebSocketSession session) {
		// 修改为支持多会话的添加方式
		USER_SESSION_MAP.computeIfAbsent(sessionKey.toString(),
				k -> new CopyOnWriteArraySet<>()).add(session);
	}

	public static void removeSession(Object sessionKey) {
		// 移除时不再自动清除所有会话
		Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
		if (sessions != null) {
			sessions.removeIf(s -> !s.isOpen()); // 只移除已关闭的连接
			if (sessions.isEmpty()) {
				USER_SESSION_MAP.remove(sessionKey.toString());
			}
		}
	}

	// 保持原有方法签名不变(兼容现有调用)
	public static WebSocketSession getSession(Object sessionKey) {
		Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
		return sessions != null ? sessions.stream().findFirst().orElse(null) : null;
	}

	// 新增方法:获取用户的所有会话
	public static Set<WebSocketSession> getSessions(Object sessionKey) {
		return USER_SESSION_MAP.getOrDefault(sessionKey.toString(), Collections.emptySet());
	}

	// 保持原有方法不变
	public static Collection<WebSocketSession> getSessions() {
		List<WebSocketSession> allSessions = new ArrayList<>();
		USER_SESSION_MAP.values().forEach(allSessions::addAll);
		return allSessions;
	}

	// 保持原有方法不变
	public static Set<String> getSessionKeys() {
		return USER_SESSION_MAP.keySet();
	}
}
相关推荐
橘子真甜~20 小时前
C/C++ Linux网络编程15 - 网络层IP协议
linux·网络·c++·网络协议·tcp/ip·计算机网络·网络层
Allen正心正念202521 小时前
网络编程与通讯协议综合解析
网络
bing_feilong21 小时前
ubuntu中的WIFI与自身热点切换
网络
CodeByV21 小时前
【网络】UDP 协议深度解析:从五元组标识到缓冲区
网络·网络协议·udp
车载测试工程师1 天前
CAPL学习-AVB交互层-概述
网络协议·tcp/ip·以太网·capl·canoe
虹科网络安全1 天前
艾体宝洞察 | 利用“隐形字符”的钓鱼邮件:传统防御为何失效,AI安全意识培训如何补上最后一道防线
运维·网络·安全
石像鬼₧魂石1 天前
Kali Linux 网络端口深度扫描
linux·运维·网络
鲸鱼电台分台1 天前
工业应用通信协议:IEC104
网络协议
适应规律1 天前
UNeXt-Stripe网络架构解释
网络
纸带1 天前
USB通信的状态
网络