首先链接的地址要先拿在websocket在线调试去调试是否能连接通 不然下面的操作就不知道错误
// 建立websocket
connectSocketInit() {
// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
uni.connectSocket({
// 【非常重要】必须确保你的服务器是成功的,如果是手机测试千万别使用ws://127.0.0.1:9099【特别容易犯的错误】
// url: 'wss://'+this.$api.sellerWebsocket+'/'+this.userinfo.id,
url: 'ws://' + this.$api.sellerWebsocket + '/' + this.userinfo.id,
success(data) {
console.log("websocket连接成功");
},
});
// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
uni.onSocketOpen(function(res) {
console.log('WebSocket连接已打开!');
});
uni.onSocketMessage(function(res) {
console.log('收到服务器内容:' + res.data);
// 语音播放 start
const innerAudioContext = uni.createInnerAudioContext();
innerAudioContext.autoplay = true;
innerAudioContext.src = 'https://wzs1.oss-cn-beijing.aliyuncs.com/music.mp3';
innerAudioContext.onPlay(() => {
console.log('开始播放');
});
innerAudioContext.onError((res) => {
console.log(res.errMsg);
console.log(res.errCode);
});
//语音播放 end
});
// 这里仅是事件监听【如果socket关闭了会执行】
uni.onSocketClose(function(res) {
console.log('WebSocket 已关闭!');
});
},
// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
beforeDestroy() {
this.closeSocket();
},
// 关闭websocket【离开这个页面的时候执行关闭】
closeSocket() {
this.socketTask.close({
success(res) {
this.is_open_socket = false;
console.log("关闭成功", res)
},
fail(err) {
console.log("关闭失败", err)
}
})
},
uniapp做WebSocket
最新推荐文章于 2024-06-18 08:42:14 发布