<template>
<div class="test">
</div>
</template>
<script>
export default {
name : 'test',
data() {
return {
websocket: null,
}
},
created() {
//创建websocket连接
this.createWebSocket();
},
destroyed() {
//关闭websocket连接
this.socket.onclose = this.socketClose();
},
methods: {
createWebSocket(){
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket('ws://10.60.2.45:9090/myWebsocket/1');
// 监听socket连接
this.socket.onopen = this.open;
// 监听socket消息
this.socket.onmessage = this.getMessage;
// 监听socket错误信息
this.socket.onerror = this.error;
// 监听关闭
this.socket.onclose = this.socketClose;
}
},
open(){
console.log("socket连接成功")
},
error(){
console.log("连接错误")
},
getMessage(e) {
console.log('监听消息',e);
const res = JSON.parse(e.data);
},
send() {
this.socket.send(params)
},
socketClose() {
console.log("socket已经关闭")
},
},
}
</script>
<style lang='less'>
</style>