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

SpringBoot搭建WebSocket初始化

1.java后端的maven添加websocket依赖

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

2.实例化ServerEndpointExporter对象,
这样才能自动调用@ServerEndpoint(“/test”)里面的方法

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

3.创建一个类,该类的功能是提供websocket服务

/*** websocket服务*/
@Component
@ServerEndpoint("/test")
public class WebsocketServer{@OnOpenpublic void onOpen(Session session, EndpointConfig endpointConfig) {System.out.println("websocket已连接");}@OnClosepublic void onClose(Session session, CloseReason closeReason) {System.out.println("websocket已关闭");}@OnErrorpublic void onError(Session session, Throwable throwable) {System.out.println("连接错误"+throwable);}//发送@OnMessagepublic void onMessage(String message,Session session){System.out.println("接收到消息:" + message);try {session.getBasicRemote().sendText("回应: " + message);} catch (Exception e) {e.printStackTrace();}}
}

前端测试发起请求连接websocket
创建了一个html,控制台输出结果

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title>
</head>
<body><script>var ws=new WebSocket("ws://localhost:8080/test");ws.onopen=function(){console.log("连接成功");ws.send('6666');}ws.onclose=function(){console.log("连接关闭");}ws.onmessage=function(res){console.log(res);}ws.onerror=function(res){console.log(res);}</script>
</body>
</html>

结果:
在这里插入图片描述

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

相关文章:

  • 节能延寿:ARM Cortex-M微控制器下的低功耗定时器应用
  • GPT突破限制回复图片
  • 微信小程序nodejs+vue+uniapp高校食堂线上预约点餐系统
  • Python 程序设计入门(006)—— 列表的操作(1):列表元素的增、删、改操作
  • 使用Python实现高效数据下采样:详解最大三角形三桶(LTTB)算法
  • 无涯教程-Perl - for 语句函数
  • 企业网盘解析:高效的企业文件共享工具
  • 前端实习day20
  • # 关于Linux下的parted分区工具显示起始点为1049kB的问题解释
  • 前端页面--视觉差效果
  • 使用idea如何生成webservice客户端
  • QT属性系统
  • CentOS 7虚拟机 虚拟机安装安装增强VBox_GAs_6.1.22失败:modprobe vboxguest failed
  • 【基础类】—DOM事件系统性学习
  • 【控制项目风险经验之谈】
  • SpringBoot复习:(10)SpringApplication中的initializer成员变量是怎么初始化的?
  • Java三大特征之继承【超详细】
  • python: lidar点云转BEV投影及pillar/voxel
  • 我的创作纪念日2023.8.5
  • 课程作业-基于Python实现的迷宫搜索游戏附源码
  • 差值结构的相互作用能
  • UI、UE、UX的区别
  • RabbitMQ 教程 | 第10章 网络分区
  • Flask学习笔记_异步论坛(四)
  • K8S系列文章之 kubeasz部署K8S环境
  • nodejs和vue的关系--vue3教程
  • 前端大屏尺寸实现自适应屏幕大小
  • leetcode 416. 分割等和子集
  • cesium加载三维模型3dtiles
  • el-select控制单选还是多选