websocket.onopen中的方法不起作用

时间:2019-04-17 15:17:45

标签: javascript vue.js websocket

我尝试创建一个websocket连接以在vue.js中发送一些数据,但是它不起作用

我尝试直接在websocket.onopen中发送数据,并在方法中定义了一个新功能,但仍然无法正常工作。但是,如果我创建一个新的js文件,然后将代码复制粘贴到该文件中,它将起作用。

_initWebsocket () { //init websocket and websocket i've defined in data
            const wsServer = 'ws://101.132.181.245:9501';
            this.websocket = new WebSocket(wsServer);
            this.websocket.onopen = function () {
                this.websocketSend() // the first way
                this.websocket.send('{"url":"/test","message":"123"}') // the second way
                console.log("Connected to WebSocket server.");
            };
            this.websocket.onclose = function () {
                console.log("Disconnected");
            };
            this.websocket.onmessage = function (evt) { 
                console.log('Retrieved data from server: ' + evt.data);
            };
            this.websocket.onerror = function (evt) {
                console.log('Error occured: ' + evt.data);
            };
        },
websocketSend () {
            this.websocket.send('{"url":"/test","message":"123"}')
        },

第一个错误代码是:

  

未捕获的TypeError:无法读取未定义的属性“发送”       在WebSocket.websocket.onopen

第二个错误代码是:

  

未捕获的TypeError:this.websocketSend不是WebSocket.websocket.onopen的函数

这是怎么了

0 个答案:

没有答案