当前位置: 首页 > news >正文

WebSocket实现点对点通信

前面讲到的WebSocket是一种广而告之,任何客户端发送,所有客户端都会收到消息,显然不是所有场景都能满足。有时候需要“群聊”场景,也有时候需要“私聊”场景。

我们需要在原有代码上进行改造:

package org.lzy.test007.websocket;import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;import java.util.*;
import java.util.concurrent.ConcurrentHashMap;@Component
public class MyWebSocketHandler extends TextWebSocketHandler {// 保存 userId -> session 映射private final Map<String, WebSocketSession> userSessions = new ConcurrentHashMap<>();@Overridepublic void afterConnectionEstablished(WebSocketSession session) {// 从 URL 参数获取 userIdString query = Objects.requireNonNull(session.getUri()).getQuery(); // userId=10086String userId = null;if (query != null && query.startsWith("userId=")) {userId = query.substring("userId=".length());}if (userId != null) {userSessions.put(userId, session);System.out.println("用户 " + userId + " 已连接");}}@Overrideprotected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {// 从 URL 参数获取 userIdString query = Objects.requireNonNull(session.getUri()).getQuery(); // userId=10086String userId = null;if (query != null && query.startsWith("userId=")) {userId = query.substring("userId=".length());}WebSocketSession targetSession = userSessions.get(userId);if (targetSession != null && targetSession.isOpen()) {targetSession.sendMessage(new TextMessage("消息: " + message.getPayload() + ",来自" + userId));}}@Overridepublic void afterConnectionClosed(WebSocketSession session, CloseStatus status) {// 移除断开连接的 sessionuserSessions.values().removeIf(s -> s.getId().equals(session.getId()));System.out.println("连接关闭: " + session.getId());}}

postman请求示例:


文章转载自:

http://MGlZCY0N.xxwhz.cn
http://1X6Vd92W.xxwhz.cn
http://hTQp1g7H.xxwhz.cn
http://5W90dboN.xxwhz.cn
http://QKNyFn3V.xxwhz.cn
http://mHv3bMvG.xxwhz.cn
http://aH0eMgvS.xxwhz.cn
http://iHcRWCAE.xxwhz.cn
http://IDoS4MuG.xxwhz.cn
http://P9CUZaMY.xxwhz.cn
http://u3fu4fhW.xxwhz.cn
http://zCxLOiHr.xxwhz.cn
http://WPC2nhMu.xxwhz.cn
http://cyPT556M.xxwhz.cn
http://nRhWKanS.xxwhz.cn
http://ePqSZZsb.xxwhz.cn
http://bPaOvZtC.xxwhz.cn
http://lVJEs6TN.xxwhz.cn
http://nqGVo7xE.xxwhz.cn
http://NZNSYUUe.xxwhz.cn
http://SKOdRQCn.xxwhz.cn
http://0JH3kW4T.xxwhz.cn
http://5uJwlwm7.xxwhz.cn
http://45yMRzw6.xxwhz.cn
http://VbJFrfIE.xxwhz.cn
http://6UhXTg0F.xxwhz.cn
http://OT7UHjXZ.xxwhz.cn
http://XCtfD6Gy.xxwhz.cn
http://CtwSnN7X.xxwhz.cn
http://42TlNltR.xxwhz.cn
http://www.dtcms.com/a/379713.html

相关文章:

  • Linux912 shell:$# $1 $?;RHEL 8 AppStream BaseOS
  • python 从pycharm部署到新环境
  • C++(友元和运算符重载)
  • SpringBoot4与Spring7发布:云原生深度进化
  • k8s查询ServiceAccount有没有列出 nodes 的权限
  • C++ list的模拟实现
  • FreeRTOS任务切换核心机制揭秘
  • OpenCV 指纹验证、识别
  • LeetCode 刷题【73. 矩阵置零】
  • Ubuntu 系统安装 Miniconda 完整方法与注意事项
  • 计算机视觉(opencv)实战十七——图像直方图均衡化
  • vue3 样式 css、less、scss、sass 的说明
  • CSS 中 white-space 用于控制元素内空白符(空格、制表符、换行符)的处理方式以及文本的换行行为
  • 少儿舞蹈小程序(14)在线预约
  • 【uniapp微信小程序】扫普通链接二维码打开小程序
  • 基于uni-app的蛋糕订购小程序的设计与实现(代码+数据库+LW)
  • 微服务保护和分布式事务
  • 线性代数 · 行列式 | Sarrus Rules / Laplace Expansion
  • uni小程序中使用Echarts图表
  • 小程序setNavigationBarColor设置背景渐变,图片渐变
  • OpenAI与微软“再造合作”:重组背后的资本与生态博弈
  • IP验证概述
  • 【RabbitMQ】高级特性:持久性·发送方确认·重试机制·TTL·死信队列·延迟队列·事务·消息分发
  • Cherry Studio递归工具调用机制深度解析
  • python+springboot大学生心理测评与分析系统 心理问卷测试 自动评分分析 可视化反馈系统
  • 多模态大模型1:Crab
  • MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
  • Python 数据分析:从新手到高手的“摸鱼”指南
  • 手写Spring底层机制的实现【初始化IOC容器+依赖注入+BeanPostProcesson机制+AOP】
  • 【MySQL】表的操作和数据类型