uniapp微信小程序结合stompjs

小程序使用stompjs,先导入@stomp/stompjs

npm install @stomp/stompjs

使用uniapp提供的api创建webosocket。

const socketTask = uni.connectSocket({
    url: 'ws://localhost:8080/endpoint' ,    // ws地址
    header: {
        'content-type': 'application/json',
	     Cookie: 'token=' + token            // 可选带上token
    }
});

由于uniapp创建的ws不能直接供stompjs使用,需要进行一下封装。

const socketWrapper = {
    send(data) {
        uni.sendSocketMessage({ data: typeof data === 'string' ? data : JSON.stringify(data) });
    },    
    close() {
        uni.closeSocket();
    },
    set onopen(fn) { uni.onSocketOpen(fn); },
    set onmessage(fn) {   
        uni.onSocketMessage((res) => {
            fn({ data: res.data });
        });
    },
	set onclose(fn) { uni.onSocketClose(fn); },
	set onerror(fn) { uni.onSocketError(fn); },
	readyState: 0
};

最后进行连接:

// Stomp.over(websokect)
const stompClient = Stomp.over(socketWrapper);

stompClient.connect(
    {},
	function (frame) {
	    console.log('✅ STOMP连接成功');
	},
	function (error) {
	    console.error('❌ STOMP连接失败', error);
    }
);

在小程序真机调试时,显示:

(in promise) MiniProgramError
TextEncoder is not defined
ReferenceError: TextEncoder is not defined
at TextEncoder (common/vendor.js:7776:25)
at StompHandler.start (common/vendor.js:8113:20)
at start (common/vendor.js:8565:24)
at s (app-service.js:1979:738)
at Generator.<anonymous> (app-service.js:1979:2075)
at Generator.next (app-service.js:1979:1101)
at asyncGeneratorStep (app-service.js:1913:58)
at c (app-service.js:1913:277)

原因是Stompjs依赖于 TextEncoderTextDecoder 等 Web API,而微信小程序并不直接支持这些 API。需要在main.js上引入Polyfill并挂载全局。

npm install text-encoding
// main.js
import { TextEncoder, TextDecoder } from 'text-encoding';  // 引入 Polyfill

// 将 Polyfill 添加到环境中
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值