vue + websocket
- 在Vue项目的入口文件(通常是main.js)中引入和配置WebSocket:
import VueNativeSock from 'vue-native-websocket';
Vue.use(VueNativeSock, 'ws://localhost:8080', {
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 3000,
});
- 新建vue组件
<template>
<!-- websocketceshi -->
<div class="layout">
<div class="msgBody">{{ msg }}</div>
<input v-model="sendMsg" style="width:200px;height:30px;margin-top:20px"/>
<button @click="sendMessage" style="width:100px;height:30px;">发送</button>
<button @click="close" style="width:100px;height:30px;">断开链接</button>
<button @click="init" style="width:100px;height:30px;">建立链接</button>
</div>
</template>
<script>
export default {
name: "LayOut",
data() {
return {
msg: "",
sendMsg: "",
path: "ws://localhost:8001/webSocket/admin",
socket: "",
};
},
methods: {
sendMessage() {
this.socket.send(this.sendMsg);
},
init() {
if (typeof WebSocket === "undefined") {
alert("您的浏览器不支持socket");
} else {
this.socket = new WebSocket(this.path);
this.socket.onopen = this.open;
this.socket.onerror = this.error;
this.socket.onmessage = this.getMessage;
this.socket.onclose = this.close;
}
},
open() {
console.log("socket连接成功");
},
error(err) {
console.log("连接错误" + err);
},
getMessage(msg) {
this.msg = msg.data;
},
close(event) {
this.socket.close()
console.log("断开链接成功");
},
},
created() {
this.init();
},
};
</script>
<style scoped>
.layout {
position: relative;
width: 100%;
height: 100%;
}
.msgBody {
width: 500px;
height: 300px;
border: 1px solid rgb(95, 79, 79);
}
</style>