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

Java 使用websocket

添加依赖

<!-- WebSocket 支持 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

添加配置类

@Configuration
public class WebSocketConfig {@Beanpublic ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter();}
}

添加服务类

@Component
@ServerEndpoint("/ws/{clientId}")
public class WebSocketServer {private static Map<String, Session> sessionMap = new HashMap<>();@OnOpenpublic void onOpen(Session session, @PathParam("clientId") String clientId) {System.err.println("客户端:" + clientId + "建立连结");sessionMap.put(clientId, session);}@OnClosepublic void onClose(@PathParam("clientId") String clientId) {sessionMap.remove(clientId);}/*** 收到客户端消息后调用的方法** @param message  客户端发送过来的消息* @param clientId*/@OnMessagepublic void onMessage(String message, @PathParam("clientId") String clientId) {System.err.println("收到来自客户端" + clientId + "的消息:" + message);}public void sendMessage(String message) {Collection<Session> sessions = sessionMap.values();for (Session session : sessions) {try {session.getBasicRemote().sendText(message);} catch (Exception e) {e.printStackTrace();}}}}

测试

在线测试地址:https://docs.wildfirechat.cn/web/wstool/index.html


http://www.mrgr.cn/news/92134.html

相关文章:

  • ClickHouse系列之ClickHouse安装
  • Linux上使用dify构建RAG
  • 第9章:LangChain结构化输出-示例4(基于大模型从自然语言中提取POJO)
  • vue:vite 代理服务器 proxy 配置
  • Go入门之struct
  • nodejs:vue 3 + vite 作为前端,将 html 填入<iframe>,在线查询英汉词典
  • Python游戏编程之赛车游戏6-2
  • 一文详解U盘启动UEFI/Legacy方式以及GPT/MBR关系
  • k8s集群部署
  • Linux常见问题
  • 【C语言】第八期——指针、二维数组与字符串
  • 关于order by的sql注入实验
  • 【Python LeetCode 专题】树
  • Ubuntu 22.04 一键部署MinerU1.1.0
  • dockerfile构建haproxy
  • superset
  • 本地部署AI模型 --- DeepSeek(一)
  • Day9 25/2/22 SAT
  • 玩机日记 13.5 群晖部署AList并配置SSL,安装opkg,使用rclone挂载到本地
  • 记录一次 ALG 的处理过程