天天看点

vue中websocket应用

data() {
    return {
        ws: null,
        wsInterval: null
    }
},
methods: {
        initWS() {
            if ('WebSocket' in window) {
                try {
                    this.ws = new WebSocket(
                        'ws://' +
                            window.location.host +
                            '/tcmp/ws/namespaces/' +
                            this.sunamespace +
                            '/pods/' +
                            this.subname +
                            '/log'
                    )
                    // this.ws = new WebSocket('ws://10.220.254.6:30050/tcmp/ws/namespaces/' + this.sunamespace + '/pods/' + this.subname + '/log');
                    this.ws.onopen = () => {
                        this.ws.send('心跳包')
                        this.wsInterval = setInterval(() => {
                            this.ws.send('心跳包')
                        }, 50000)
                    }
                    this.ws.onmessage = (evt) => {
                        console.log(evt.data)
                        /*if (this.monacoEditor) {
                            this.monacoEditor.setValue(
                                this.monacoEditor.getValue() +
                                    '\n' +
                                    Base64.decode(evt.data)
                            )
                            const count =
                                this.monacoEditor.getModel().getLineCount() || 0
                            this.monacoEditor.revealLine(count)
                            this.monacoEditor
                                .getAction('editor.action.formatDocument')
                                ._run()
                        }*/
                    }
                    this.ws.onclose = () => {
                        this.clearWsInterval()
                    }
                    this.ws.onerror = () => {
                        this.notifyInfo('webSocket 连接失败!')
                        this.clearWsInterval()
                    }
                } catch (error) {
                    this.notifyInfo('webSocket 连接失败!')
                    this.clearWsInterval()
                }
            }
        },
        notifyInfo(message) {
            this.$notify({
                title: '提醒',
                message: message,
                offset: 200
            })
        },
        clearWsInterval() {
            if (this.wsInterval) {
                window.clearInterval(this.wsInterval)
            }
        }
}
           

继续阅读