新建WebSocketService.js
export default class WebSocketService {
constructor(url, getSocketMsg, sendSucc) {
this.url = url;
this.getSocketMsg = getSocketMsg;
this.sendSucc = sendSucc; // 发送命令成功后的回调,可有可无
this.socketTask = null;
this.isOpenSocket = false;
this.socketPrestore = {
state: false,
data: null
};
}
connect() {
this.socketTask = uni.connectSocket({
url: this.url,
success: ()=>{
console.log('正在建立socket链接:', this.url);
},
});
this.socketTask.onOpen(() => {
console.log("WebSocket连接已发开...!");
this.isOpenSocket = true;
if (this.socketPrestore.state) {
this.sendSocketData(this.socketPrestore.data);
this.socketPrestore.state = false;
}
});
this.socketTask.onMessage((res)=>{
this.getSocketMsg(res)
});
this.socketTask.onClose(() => {
this.isOpenSocket = false;
});
};
sendSocketData(data) {
if (this.isOpenSocket) {
const sendData = JSON.stringify(data);
console.log("发送socket数据:", sendData);
this.socketTask.send({
data: sendData,
success: ()=>{
console.log("socket消息发送成功");
this.sendSucc && this.sendSucc()
}
});
} else {
this.socketPrestore.data = data;
this.socketPrestore.state = true;
this.connect(this.url)
}
};
close() {
if (this.isOpenSocket) {
this.socketTask.close();
this.isOpenSocket = false;
}
}
}
关于socketPrestore
部分代码处理机制是根据我的业务添加的,防止发送命令的时候socket
链接被服务主动断开做的机制处理,若不需要直接删除就行。
方法调用
<script>
//引入websocket文件
import WebSocketService from '@/utils/WebSocketService.js'
export default {
data() {
return {
socket: null,
}
},
mounted() {
const url = 'wss://.....'// socket地址
this.socket = new WebSocketService(url, this.receiveSocketData, this.sendSucc)
},
methods: {
receiveSocketData(res){
console.log('接收到socket数据:', res);
},
sendSucc(){
console.log('发送命令成功后的回调');
}
}
}
</script>