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

Springboot2+WebSocket

一、引入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

二、添加配置

新增配置文件

config/WebSocketConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;@Configuration
public class WebSocketConfig {/*** 这个Bean的作用是自动注册使用了@ServerEndpoint注解的Bean*/@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}

三、新建互通类

/*** description:  平台同步*/
@Component
@Slf4j
// 类似于controlelr 服务点
@ServerEndpoint(value = "/webSocket/{username}")
public class PlatformAsyncWebSocket {/**静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。*/private static int onlineCount = 0;/**concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。*/private static ConcurrentHashMap<String,PlatformAsyncWebSocket> webSocketMap = new ConcurrentHashMap<>();/**与某个客户端的连接会话,需要通过它来给客户端发送数据*/private Session session;/**接收userId*/private String username="";/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session,@PathParam("username") String username) {this.session = session;this.username=username;if(webSocketMap.containsKey(username)){webSocketMap.remove(username);webSocketMap.put(username,this);//加入set中}else{webSocketMap.put(username,this);//加入set中addOnlineCount();//在线数加1}log.info("用户连接:"+username+",当前在线人数为:" + getOnlineCount());try {sendMessage("连接成功");} catch (IOException e) {log.error("用户:"+username+",网络异常!!!!!!");}}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {if(webSocketMap.containsKey(username)){webSocketMap.remove(username);//从set中删除subOnlineCount();}log.info("用户退出:"+username+",当前在线人数为:" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(String message, Session session) {log.info("用户消息:"+username+",报文:"+message);//可以群发消息//消息保存到数据库、redisif(StringUtils.isNotBlank(message)){try {//解析发送的报文JSONObject jsonObject = JSON.parseObject(message);//追加发送人(防止串改)jsonObject.put("fromUserId",this.username);String toUserId=jsonObject.getString("toUserId");//传送给对应toUserId用户的websocketif(StringUtils.isNotBlank(toUserId)&&webSocketMap.containsKey(toUserId)){webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());}else{log.error("请求的userId:"+toUserId+"不在该服务器上");//否则不在这个服务器上,发送到mysql或者redis}}catch (Exception e){e.printStackTrace();}}}/**** @param session* @param error*/@OnErrorpublic void onError(Session session, Throwable error) {log.error("用户错误:"+this.username+",原因:"+error.getMessage());error.printStackTrace();}/*** 实现服务器主动推送*/public void sendMessage(String message) throws IOException {this.session.getBasicRemote().sendText(message);}/*** 发送自定义消息* */public static void sendMsg(String message,@PathParam("username") String username) throws IOException {log.info("发送消息到:"+username+",报文:"+message);if(StringUtils.isNotBlank(username)&&webSocketMap.containsKey(username)){webSocketMap.get(username).sendMessage(message);}else{log.error("用户"+username+",不在线!");}}public static synchronized int getOnlineCount() {return onlineCount;}public static synchronized void addOnlineCount() {PlatformAsyncWebSocket.onlineCount++;}public static synchronized void subOnlineCount() {PlatformAsyncWebSocket.onlineCount--;}}

http://www.lryc.cn/news/246255.html

相关文章:

  • 希尔伯特和包络变换
  • 国产Ai大模型和chtgpt3.5的比较
  • 机器学习ROC曲线中的阈值thresholds
  • MySOL常见四种连接查询
  • 数智融合 开启金融数据治理新时代
  • 数据结构——利用堆进行对数组的排序
  • Unity 场景切换
  • 【PTA题目】7-12 N个数求和 分数 20
  • 智能AIGC写作系统ChatGPT系统源码+Midjourney绘画+支持GPT-4-Turbo模型+支持GPT-4图片对话
  • List转string 逗号分隔
  • 手机文件怎么传到电脑?简单方法分享!
  • 计算机基础知识59
  • RK3568基于openharmony3.2版本之MIPI屏幕调试
  • pycharm安装PyQt5及其工具
  • 百度人工智能培训第一天笔记
  • 阿里云ACE认证之国际版与国内版对比!
  • Java 简易版王者荣耀
  • 【Linux】 file命令使用
  • MFC设置单选按钮点击自己可以可选和不可选
  • 【数据结构】二叉树之链式结构
  • 完美的输出打印 SQL 及执行时长[MyBatis-Plus系列]
  • 跨标签页通信的8种方式(下)
  • 笔记二十、使用路由Params进行传递参数
  • K8S----taint、tolerations、label
  • 【双指针】三数之和
  • CH01_适应设计模式
  • 电机工作制
  • qt国际化多语言
  • Java Excel Poi 单元格内置的数据格式
  • 【深入剖析K8s】容器技术基础(三):深入理解容器镜像 文件角度