- Vue 프로젝트에 WebSocket 라이브러리 설치
npm install --save vue-native-websocket
- main.js 글로벌 구성
import websocket from 'vue-native-websocket';
Vue.use(websocket, '', {
connectManually: true,
format: 'json',
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 2000,
});
- WebSocket 연결 만들기
export default {
data() {
return {
socket:null,
}
},
mounted() {
if(this.socket){
this.socket.close()
console.log('socket关闭1')
}
},
created() {
},
destroyed() {
if(this.socket){
this.socket.close()
console.log('socket关闭1')
}
},
methods: {
initWebSocket() {
if (typeof WebSocket === "undefined") {
alert("您的浏览器不支持socket");
} else {
let WSUrl = ‘ws://10.0.0.121:8700/camera/ws’;
this.socket = new WebSocket(`${
WSUrl}`);
this.socket.onopen = this.open;
this.socket.onerror = this.error;
this.socket.onmessage = this.getMessage;
this.socket.onsend = this.send;
this.socket.onclose = this.close;
}
},
open() {
this.socket.send(JSON.stringify({
"app": "start"}));
console.log("socket连接成功");
},
error() {
console.log("连接错误");
this.socket = null;
const timer = setTimeout(() => {
this.initWebSocket();
this.WS.wsCount++;
}, 5000);
if (this.WS.wsCount > 4) {
clearTimeout(timer);
}
},
getMessage(msg) {
console.log(JSON.parse(msg.data));
},
send(Data) {
console.log('数据发送')
this.websock.send(Data)
},
close() {
console.log("socket已经关闭");
},
}
}