websocket使用方法|vue实时推送

WebSocket实时推送

创建一个WebSocket对象:

准备变量

mounted() {
    // 初始化
    const uri = window.location.href; // 获取网页url
    const protocol = uri.split("/")[0]; // https: 确定当前传输协议
    const domain = uri.split("/")[2]; // Iip:port
    const wsProtocol = protocol === "https:" ? "wss" : "ws"; // 选择需要的协议
    this.path = `${wsProtocol}://${domain}/xxx`; // xxx为请求地址

    this.init(); // 进入websocket初始化程序
},

初始化

init() {
    if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
    } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
    }
},

连接成功时

open() {
    console.log("socket连接成功");
},

连接失败时

error() {
    console.log("连接错误");
},

接收到信息时

getMessage(msg) {
    if (msg.data) {
        this.list = JSON.parse(msg.data);
        console.log(this.list)
    }
},

发送信息时

send() {
    this.socket.send(params);
},

连接关闭时

close() {
    console.log("socket已经关闭");
},

本文作者:朝颜浅语

本文链接:https://www.cnblogs.com/ommggg/p/17896656.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   朝颜浅语  阅读(80)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起