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

uni-app + SpringBoot +stomp 支持websocket 打包app

文章目录

  • 一、概述:
  • 二、配置:
    • 1. 后端配置
    • 2. uni-app(app端)
    • 3. 使用

一、概述:

websocket 协议是在http 协议的基础上的升级,通过一次http 请求建立长连接,转而变为TCP 的全双工通信;而http 协议是一问一答的请求方式方式。

二、配置:

1. 后端配置

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{@Overridepublic void registerStompEndpoints(StompEndpointRegistry registry) {//注册STOMP协议的节点(endpoint),并映射指定的url//注册一个STOMP的endpoint,并指定使用SockJS协议// 此处配置支持PC 端浏览器,客户端访问采用http registry.addEndpoint("/websocket").setAllowedOriginPatterns("*").withSockJS();// 此处配置支持uniapp  app 端打包,不要带withSockJS, 客户端访问 采用ws 协议registry.addEndpoint("/websocket-app").setAllowedOriginPatterns("*");}@Overridepublic void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(Message Broker)//广播式应配置一个/topic消息代理registry.enableSimpleBroker("/topic");}
}

2. uni-app(app端)

websocket-uni.js

let socketOpen = false;
let socketMsgQueue = [];
import http from "@/common/Http.vue";export default {client: null,baseURL: `ws://192.168.1.1:9109/websocket-app`,//uni-app使用时不能使用http不然监听不到,需要使用wsinit(headers) {if (this.client) {return Promise.resolve(this.client);}return new Promise((resolve, reject) => {const ws = {send: this.sendMessage,onopen: null,onmessage: null,close: this.closeSocket,};uni.connectSocket({url: this.baseURL,header: headers,success: function() {console.log("WebSocket连接成功");}});uni.onSocketOpen(function(res) {console.log('WebSocket连接已打开!', res);socketOpen = true;for (let i = 0; i < socketMsgQueue.length; i++) {ws.send(socketMsgQueue[i]);}socketMsgQueue = [];ws.onopen && ws.onopen();});uni.onSocketMessage(function(res) {console.log("回馈")ws.onmessage && ws.onmessage(res);});uni.onSocketError(function(res) {console.log('WebSocket 错误!', res);});uni.onSocketClose((res) => {this.client.disconnect();this.client = null;socketOpen = false;console.log('WebSocket 已关闭!', res);});const Stomp = require('./stomp.js').Stomp;Stomp.setInterval = function(interval, f) {return setInterval(f, interval);};Stomp.clearInterval = function(id) {return clearInterval(id);};const client = this.client = Stomp.over(ws);client.connect(headers, function() {console.log('stomp connected');resolve(client);});});},disconnect() {uni.closeSocket();},sendMessage(message) {if (socketOpen) {uni.sendSocketMessage({data: message,});} else {socketMsgQueue.push(message);}},closeSocket() {console.log('closeSocket');},
};

3. 使用

	import WebSocket from '@/components/js/websocket-uni1.js';if (self.map.get("token")) {//需要上传tokenheaders.Authorization = self.map.get("token");}WebSocket.init(headers).then(client => {//接收反馈端口,成功方法,错误方法client.subscribe('/topic/getResponse', this.responseCallback, this.onFailed);});responseCallback: function(frame) {let self=this;let body = JSON.parse(frame.body);uni.showToast({icon:"success",icon: 'none',position:"center",title:"消息:您有一个新的消息,请注意接收"},2000)},onFailed: function(frame) {//this.$notify.error({//  title: '系统错误',//  message: '消息服务连接失败!',//});console.log('STOMP: ' + frame);},
http://www.lryc.cn/news/134691.html

相关文章:

  • LeetCode--HOT100题(35)
  • idea插件grep console最佳实践
  • Android 12 源码分析 —— 应用层 二(SystemUI大体组织和启动过程)
  • 【C#】通用类型转换
  • 传统DNS、负载均衡服务发现框架与专业服务发现框架(Eurek、nacos)分析
  • js中数组常用操作函数
  • Windows、Mac、Linux端口占用解决
  • 企业文件透明加密软件——「天锐绿盾」数据防泄密管理软件系统
  • Postman接口自动化测试实例
  • 软件团队降本增效-构建人员评价体系
  • Python实现SSA智能麻雀搜索算法优化随机森林分类模型(RandomForestClassifier算法)项目实战
  • web JS高德地图标点、点聚合、自定义图标、自定义窗体信息、换肤等功能实现和高复用性组件封装教程
  • AlpacaFarm: A Simulation Framework for Methods that Learn from Human Feedback
  • 【Linux】Linux工具篇(yum、vim、gcc/g++、gdb、Makefile、git)
  • 自己实现 SpringMVC 底层机制 系列之-实现任务阶段 5- 完成 Spring 容器对象的自动装配 -@Autowried
  • linux的http服务
  • Restful架构简单了解
  • conda常用命令
  • Linux:shell脚本:基础使用(6)《正则表达式-awk工具》
  • 国际阿里云腾讯云:阿里云服务器怎么打包
  • FPGA中锁存器(latch)、触发器(flip-flop)以及寄存器(register)详解
  • 【正点原子STM32连载】第十八章 通用定时器PWM输出实验 摘自【正点原子】APM32F407最小系统板使用指南
  • 分类预测 | MATLAB实现BWO-TCN-Attention数据分类预测
  • 6.链路追踪-Zipkin
  • 基于ACF,AMDF算法的语音编码matlab仿真
  • python 基础篇 day 1 初识变量和数据类型
  • Window下部署使用Stable Diffusion AI开源项目绘图
  • 【MySQL】好好学习一下InnoDB中的页
  • git开发常用命令
  • WEB APIs day5