websocket使用方法|vue实时推送

发布时间 2023-12-12 14:11:12作者: 朝颜浅语

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已经关闭");
},