WebSocket返回未定义的代码,但未在控制台中返回

时间:2018-10-02 19:41:11

标签: javascript websocket

我正在努力了解这里发生的事情...

我在192.168.1.64:81上有一个websocket服务器

我需要使用以下javascript将数据从网页发送到套接字:

window.onload = function() {
    var connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
    connection.onopen = function() {
        connection.send('Connect ' + new Date());
    };
    connection.onerror = function(error) {
        console.log('WebSocket Error ', error);
    };
    connection.onmessage = function(e) {
        console.log('Server: ', e.data);
    };

    function sendData() {
        var data="#"+joystick.deltaX()+","+joystick.deltaY();
        connection.send(data);
    }};

现在这是发生的情况:如果我打开js控制台(在firefox中),则会看到“连接未定义”错误...但是如果我将其复制粘贴到控制台,则该行:

    var connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);

正确定义了套接字,更新程序开始通过套接字正确地传输数据!

我想念什么? 我应该知道一些众所周知的问题吗?

1 个答案:

答案 0 :(得分:0)

以下函数使用connection变量,但是该变量超出范围,因为connection是使用var(本地)关键字定义的:

connection.onopen = function() {
    connection.send('Connect ' + new Date());
};
function sendData() {
    var data="#"+joystick.deltaX()+","+joystick.deltaY();
    connection.send(data);
}};

将`connection定义为全局值:

connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);

或使用内部绑定/引用:

connection.onopen = function(e) {
    e.target.send('Connect ' + new Date());
};
sendData = function() {
    var data="#"+joystick.deltaX()+","+joystick.deltaY();
    this.send(data);
}.bind(connection);

否则,将连接初始化为全局连接并分配如下的onload:

    var connection;
window.onload = function() {
        connection = new WebSocket("ws://"+location.hostname+":81", ['arduino']);
        connection.onopen = function() {
            connection.send('Connect ' + new Date());
        };
        connection.onerror = function(error) {
            console.log('WebSocket Error ', error);
        };
        connection.onmessage = function(e) {
            console.log('Server: ', e.data);
};};