H5端代码
//定位一个socket let socket = ref(null);
// 初始化Socket
function initWebSocket() {
socket.value = new WebSocket('wss://*******/wss');
socket.value.onopen = () => { // console.log('WebSocket 连接已建立');
};
socket.value.onmessage = async (e) => { const data = JSON.parse(e.data); if (data.type == 'init') { setTimeout(() => { //发送消息 sendMessage(data.client_id) },500) }else if(data.type == 'command') { //接受到小程序返回的数据,进行业务处理 // let valueObj: { [key: string]: string } = {}; // valueObj[arFieldSave.value || 'ar_json'] = data.content; // VFormRenderRef.value.setFormData(valueObj);
}
};
socket.value.onerror = (err) => { // console.error('WebSocket 错误:', err); };
socket.value.onclose = () => { // console.log('连接断开,尝试重连...'); setTimeout(initWebSocket, 3000); };
}
// 发送消息
const sendMessage = (id) => {
if (!socket.value || socket.value.readyState !== socket.value.OPEN) { // console.log('未建立连接'); return; } let client_id = localStorage.getItem('client_id'); var temp = { type: 'command', client_id: client_id, content: id, timestamp: Date.now() } //发送消息 socket.value.send(JSON.stringify(temp));
};
onMounted(()=>{
// 初始化Socket initWebSocket();
})
/**页面卸载,关闭socket */ onUnmounted(() => { if (socket.value) socket.value.close(); });
-------H5代码结束-------
uniapp微信小程序端代码
第一步:新建一个socket.js文件,用来存放socket代码
socket.js内容 let Socket = { WS: null, socketOpen: false, isConnecting: false, clientId:'', H5ClientId:'', // 初始化 init() { if (this.isConnecting) { return } if (!this.WS || (this.socketOpen && this.WS.readyState != 1)) { console.log('进来初始化socket啦') this.isConnecting = true this.WS = uni.connectSocket({ url: 'wss://***********-/wss', complete: () => {} }); this.onError(); this.onClose(); this.onOpen(); this.onMessage() }
},
onError() {
this.WS.onError(function(err) {
console.log('WebSocket连接打开失败,请检查!' + JSON.stringify(err));
this.isConnecting = false
})
},
onClose() {
this.WS.onClose(function() {
console.log('WebSocket 已关闭!');
this.isConnecting = false
})
},
onMessage(cb) {
// 监听服务器内容
this.WS.onMessage( async res => {
try {
let result = JSON.parse(res.data);
console.log(result)
if (result.type == 'init') {
uni.setStorageSync('initSocketMsg', result.client_id)
//把微信小程序初始化的 client_id 保存起来,用于web链接传入到H5里面,H5发送消息时需要用到这个微信小程序的client_id
this.clientId = result.client_id
} else if (result.type == 'command') {
//把H5初始化的 client_id 保存起来,微信小程序发送消息时需要用到这个H5的client_id
this.H5ClientId = result.content
}
} catch (e) {
console.log('解析错误');
}
});
},
onOpen() {
this.WS.onOpen((res) => {
console.log('WebSocket连接已打开!');
this.socketOpen = true;
this.isConnecting = false
});
},
sendMsg(msg) {
if (this.socketOpen && this.WS.readyState == 1) {
uni.sendSocketMessage({
data: msg,
success: (e) => console.log('消息发送成功',e),
fail: (err) => console.error('发送失败:', err)
})
}
},
sendCommand(data) {
var temp = {
type: 'command',
client_id: this.H5ClientId,
content: data,
timestamp: Date.now()
}
this.sendMsg(JSON.stringify(temp))
}
}
export default Socket
第二步:web.vue页面
-------微信小程序代码结束-------