Vue中使⽤websocket的正确使⽤⽅法原⽂:
<template>
<div class="test">
</div>
</template>
<script>
export default {
name : 'test',
data() {
return {
websock: null,
}
},
created() {
this.initWebSocket();
},
destroyed() {
this.websock.close() //离开路由之后断开websocket连接
},
methods: {
initWebSocket(){ //初始化weosocket
const wsuri = "ws://127.0.0.1:8080";
this.websock = new WebSocket(wsuri);
ssage = this.websocketonmessage;
pen = this.websocketonopen;
r = this.websocketonerror;
lose = this.websocketclose;
},
websocketonopen(){ //连接建⽴之后执⾏send⽅法发送数据
let actions = {"test":"12345"};
this.websocketsend(JSON.stringify(actions));
},
websocketonerror(){//连接建⽴失败重连
this.initWebSocket();
},
websocketonmessage(e){ //数据接收
const redata = JSON.parse(e.data);
},
websocketsend(Data){//数据发送
this.websock.send(Data); },
websocketclose(e){ //关闭console.log('断开连接',e); },
},
}
websocket和socket
</script>
<style lang='less'>
</style>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论