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

springboot websocket 服务端

在Spring Boot中使用WebSocket实现服务端和Java客户端的实时通信,可以分为几个步骤来完成。这里将详细介绍服务端和Java客户端的具体实现。
服务端设置
添加依赖: 在pom.xml文件中添加Spring WebSocket的依赖。

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

配置WebSocket处理器: 创建一个配置类来注册WebSocket的Endpoint。

   import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {private final WebSocketHandler webSocketHandler;public WebSocketConfig(WebSocketHandler webSocketHandler) {this.webSocketHandler = webSocketHandler;}@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(webSocketHandler, "/ws/chat").addInterceptors(new HttpSessionHandshakeInterceptor()).setAllowedOrigins("*");}}
   import org.springframework.context.annotation.Configuration;import org.springframework.web.socket.config.annotation.EnableWebSocket;import org.springframework.web.socket.config.annotation.WebSocketConfigurer;import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;import org.springframework.web.socket.WebSocketHandler;import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;@Configuration@EnableWebSocketpublic class WebSocketConfig implements WebSocketConfigurer {private final WebSocketHandler webSocketHandler;public WebSocketConfig(WebSocketHandler webSocketHandler) {this.webSocketHandler = webSocketHandler;}@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {registry.addHandler(webSocketHandler, "/ws/chat").addInterceptors(new HttpSessionHandshakeInterceptor()).setAllowedOrigins("*");}}


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

相关文章:

  • HarmonyOS】ArkTS学习之基于TextTimer的简易计时器的elapsedTime最小时间单位问题
  • Java项目: 基于SpringBoot+mybatis+maven网上租贸系统(含源码+数据库+毕业论文)
  • Computer Exercise
  • idea插件开发的第二天-写一个时间查看器
  • VMware时提示系统尚未修改安装失败
  • android系统源码12 修改默认桌面壁纸--SRO方式
  • 【AcWing】852. spfa判断负环
  • Cortex-A7:ARM官方推荐的嵌套中断实现机制
  • GitHub每日最火火火项目(9.7)
  • 二、Maven工程的创建--JavaSEJavaEE
  • Kafka 分布式消息系统详细介绍
  • Android之外部存储可以访问哪些文件夹
  • SpringBoot开发——整合JDBC
  • 自定义view中常用到哪些方法作用分别是什么
  • web登录校验
  • YOLOv8改进 | Conv篇 | YOLOv8引入DWR
  • 改写二进制文件
  • The One You Love 你爱的那个人
  • 数据库面试题学习
  • 后仿真中《建立违例和保持违例》你死板思维了吗?