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

vue使用websocket与springboot通信

WebSocket是HTML5下一种新的协议,它实现了浏览器与服务器全双工通信,能更好的节省服务器资源和带宽并达到实时通讯的目的

在很多项目中,都要用到websocket,使得前端页面与后端页进行实时通信,例如,实时查询订单状态、设备状态实时显示到页面。本博文,分为前端页面代码和后端页面代码,在最后有源代码下载链接。前端使用用vue技术,后端使用springboot

一、后端代码
1、websocket代码
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/order")
public class WebsocketProvider {/*** 连接事件,加入注解* @param session*/@OnOpenpublic void onOpen(Session session) {String orderId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);log.info("Websocket连接已打开,当前orderId为:"+orderId);// 添加到session的映射关系中WebsocketUtil.addSession(orderId, session);//测试发送消息WebsocketUtil.sendMessage(orderId, AjaxResult.success("恭喜,已建立连接"));}/*** 连接事件,加入注解* 用户断开链接* @param session*/@OnClosepublic void onClose(Session session) {String orderId = WebsocketUtil.getParam(WebsocketUtil.sessionKey, session);// 删除映射关系WebsocketUtil.removeSession(orderId);}/*** 当接收到用户上传的消息* @param session*/@OnMessagepublic void onMessage(Session session, String message) {log.info("收到Websocket消息:"+message);}/*** 处理用户活连接异常* @param session* @param throwable*/@OnErrorpublic void onError(Session session, Throwable throwable) {try {if (session.isOpen()) {session.close();}} catch (IOException e) {e.printStackTrace();}throwable.printStackTrace();}
}
2、controller发送代码
@Slf4j
@RestController
@RequestMapping("/send")
@Api(tags = "SendController", description = "发送管理")
public class SendController {/*** 相关信息**/@GetMappingpublic String getPayType(String data) {WebsocketUtil.sendMessage("123456", AjaxResult.success(data));return "发送成功";}
}
3、后端向前端发送消息代码
/*** 根据用户ID发送消息** @param result*/public static void sendMessage(String sessionId, AjaxResult result) {sendMessage(sessionId, JSON.toJSONString(result));}/*** 根据用户ID发送消息** @param message*/public static void sendMessage(String sessionId, String message) {Session session = ONLINE_SESSION.get(sessionId);//判断是否存在该用户的session,判断是否还在线if (session == null || !session.isOpen()) {return;}sendMessage(session, message);}
二、VUE前端代码
1、界面代码
<div style="display: flex;"><el-input v-model="sendData" placeholder="请输入要发送的内容"/><el-button type="success" @click="send" style="margin-left: 20px;">发送</el-button></div><div style="margin-top: 25px;margin-bottom: 5px;font-weight: bold;">收到的消息:</div><div v-for="(item,index) in messages"><span>{{item}}</span></div>
2、websocket相关代码
        console.log('进入状态监听*******')var url = payServerUrl+"?orderId="+orderId;//建立webSocket连接proxy.websocket = new WebSocket(url);//打开webSokcet连接时,回调该函数proxy.websocket.onopen = () =>{console.log("连接建立");} //关闭webSocket连接时,回调该函数proxy.websocket.onclose = () =>{console.log("连接关闭");} //接收信息proxy.websocket.onmessage = function (res) {var obj = eval('(' + res.data + ')');console.log(obj)proxy.messages.push(res.data)}
三、测试
1、后端服务启动,运行ServerApplication (运行前,maven先下载依赖包)

2、前端服务启动

window,运行cmd命令,进行前端页面文件夹,执行如下命令

(1)1、安装依赖包
npm install
(2)、启动服务
npm run dev

打开页面 :http://localhost:6080/#/index3、前端页向后端发送数据
4、后端向前端页面发送数据

​使用apifox来发发送请求,apifox百度下载即可
GET请求,http://localhost:8080/ck/send,数据为data

4、源代码:

链接:https://pan.baidu.com/s/1YnuBFQBt2O4GIdcs4jO1SA?pwd=8ahq 
提取码:8ahq

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

相关文章:

  • ChatGPT 实际上是如何工作的?
  • 【SSD1306 OLED屏幕测试程序 (开源)orangepi zero2 全志H616 】.md updata: 23/11/07
  • 【python VS vba】(5) 在python中使用xlwt操作Excel(待完善ing)
  • 【Redis】Redis整合SSMRedis注解式缓存Redis中的缓存穿透、雪崩、击穿的原因以及解决方案(详解)
  • Linux文件系统的功能规划
  • 入门 SpringCloudStream 之 RocketMq 实践全集
  • 论文阅读:Ensemble Knowledge Transfer for Semantic Segmentation
  • 定义函数(简单介绍)-def
  • Mac VsCode g++编译报错:不支持C++11语法解决
  • react_12
  • Android Mvp案例解析
  • vue的双向绑定的原理,和angular的对比
  • 平衡树相关笔记
  • ASP.net C# 用Aspose.pdf实现pdf合并
  • C语言实现原码一位除
  • three.js点滴yan(整理后)
  • VMware安装CentOS最小化开发环境导引
  • 服务器端编程/数据库驱动程序/RESTful API:介绍
  • Qwt QwtThermo绘制温度计
  • U_boot介绍
  • Flink -- window(窗口)
  • 原语:串并转换器
  • 没网络也能安装.Net 3.5!如何脱机安装.NET Framework 3.5
  • JVM运行时数据区-虚拟机栈
  • Java中介者模式
  • 前端框架Vue学习 ——(五)前端工程化Vue-cli脚手架
  • App备案-iOS云管理式证书 Distribution Managed 公钥及证书SHA-1指纹的获取方法
  • Spring -Spring之依赖注入源码解析
  • Spire.Office for .NET 8.10.2 同步更新-Crk
  • MFC 基础篇(一)