那些原理,和什么情况下时候适合用WebSocket我这就不多说,直接上代码(哈哈...拷贝即用):
<template>
<div class="box">
<a-input-search
placeholder="请输入你要发送的消息"
@search="websocketsend"
enterButton="发消息"
size="large"
v-model="value"
/>
<div class="mt20 btn">
<a-button type="primary" @click="initWebSocket">建立链接</a-button>
<a-button type="primary" @click="websocketclose">断开连接</a-button>
</div>
</div>
</template>
<script>
export default {
name: 'websocket',
data() {
return {
value: '后端的同学您好!我开始像你发起请求了!',
wsUri: 'ws://127.0.0.1:9004/webSocket/' + this.$route.query.id,
id: this.$route.query.id,//请求的链接ID
isWebSocket: false,//判断是否链接成功!
}
},
created() {
this.initWebSocket();
console.log("您请求的链接id:", this.$route.query.id)
},
destroyed() {
this.websock.close() //离开路由之后断开websocket连接
},
methods: {
initWebSocket() { //初始化weosocket
this.websock = new WebSocket(this.wsUri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
},
websocketonopen() { //连接建立之后执行send方法发送数据
this.isWebSocket = true;
console.log("链接成功!", this.isWebSocket)
// this.websocketsend(JSON.stringify(actions));
},
websocketonerror() {//连接建立失败重连
this.$message.info("重新建立链接中");
this.initWebSocket();
},
websocketonmessage(e) { //数据接收
// const redata = JSON.parse(e.data);
console.log("redata", e.data)
},
websocketsend(Data) {//数据发送
let actions = {
"msg": this.value,
"id": this.id
};
console.log("您正在发送消息", actions);
if (this.isWebSocket) {
this.websock.send(JSON.stringify(actions));
} else {
console.log("请先建立链接");
this.$message.error("请先建立链接")
}
},
websocketclose(e) { //关闭
this.isWebSocket = false;
this.websock.close();
console.log('断开连接', e);
},
}
}
</script>
<style scoped lang="scss">
.box {
margin-top: 20px;
width: 500px;
margin-left: 100px;
.btn {
button {
margin: 0 10px;
}
}
}
</style>
路由配置:
{
path: '/websocket',
name: 'websocket',
meta: {check: false},
component: resolve=> require.ensure([],()=>resolve(require('../views/websocket/index')),'index')
},
下面我们来建立一下链接看下:
发送一下消息:
测试下断开连接:
测试下断开连接后发送消息:
哈哈一切都正常,来再建立链接 ,发送消息:
后端代码请看下面这篇文章: