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

文章目录

一、概述:

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

二、配置:

1. 后端配置

java 复制代码
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer{

	 @Override
     public 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("*");

     }

     @Override
     public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(Message Broker)
         //广播式应配置一个/topic消息代理
         registry.enableSimpleBroker("/topic");

     }
}

2. uni-app(app端)

websocket-uni.js

java 复制代码
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不然监听不到,需要使用ws
    init(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. 使用

java 复制代码
	import WebSocket from '@/components/js/websocket-uni1.js';
	if (self.map.get("token")) {//需要上传token
		headers.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);
	},
相关推荐
new出一个对象5 小时前
uniapp接入BMapGL百度地图
javascript·百度·uni-app
new出一个对象5 小时前
uniapp接入高德地图
uni-app
dccose7 小时前
vue3 uniapp 扫普通链接或二维码打开小程序并获取携带参数
小程序·uni-app
弗拉唐7 小时前
springBoot,mp,ssm整合案例
java·spring boot·mybatis
2401_857610038 小时前
SpringBoot社团管理:安全与维护
spring boot·后端·安全
凌冰_8 小时前
IDEA2023 SpringBoot整合MyBatis(三)
spring boot·后端·mybatis
天天进步20159 小时前
Vue+Springboot用Websocket实现协同编辑
vue.js·spring boot·websocket
乌啼霜满天24910 小时前
Spring 与 Spring MVC 与 Spring Boot三者之间的区别与联系
java·spring boot·spring·mvc
tangliang_cn10 小时前
java入门 自定义springboot starter
java·开发语言·spring boot