美文网首页Coding is cool
vue中使用原生websocket

vue中使用原生websocket

作者: xilong | 来源:发表于2018-12-17 15:38 被阅读228次

1、优化和服务端

参考了网上几篇文章,对其中代码做了优化,加了重连机制,添加相应注释。

我刚尝试的时候因为没有websocket服务端,无意中发现一个免费的服务端。一个帅哥服务端

如果你想自己玩玩WebSocket, 但是你又不想自己部署一个WebSocket服务器,你可以使用ws = new WebSocket('wss://echo.websocket.org/'), 你向echo.websocket.org发送消息,它会回复你同样的消息。

2、代码(在vue当中)

data() {
    return {
        websock: null,
        errorSetInerval:'',
    }
},
created() {
    this.initWebSocket();
},
destroyed() {
    clearInterval(this.errorSetInerval);   //离开清除轮询
    this.websock.close() //离开路由之后断开websocket连接
},
methods: {
    initWebSocket(){ //初始化weosocket
        const wsuri = "wss://echo.websocket.org/";
        this.websock = new WebSocket(wsuri);
        this.websock.onopen = this.websocketonopen;     //建立连接
        this.websock.onmessage = this.websocketonmessage;    //广播成功
        this.websock.onerror = this.websocketonerror;        //连接断开,失败
        this.websock.onclose = this.websocketclose;          //连接关闭
    },
    websocketonopen(){  //连接成功清除 轮询
        clearInterval(this.errorSetInerval);
    },
    websocketonerror(){//连接失败 轮询
        this.initWebSocket();
        this.errorSetInerval = setInterval( () =>{
            this.initWebSocket();
        },5000)
    },
    websocketonmessage(e){ //数据接收
        const redata = JSON.parse(e.data);
    },
    websocketsend(Data){//数据发送
        let thedata = JSON.stringify(Data)
        this.websock.send(thedata);
    },
    websocketclose(e){  //关闭
        console.log('断开连接',e);
    },
},

相关文章

网友评论

    本文标题:vue中使用原生websocket

    本文链接:https://www.haomeiwen.com/subject/abcckqtx.html