小程序使用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依赖于 TextEncoder
和 TextDecoder
等 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;