Skip to content Skip to sidebar Skip to footer

Websocket Returns Undefined In Code But Not In Console

I'm struggling to understand what's happening here... I have a websocket server on 192.168.1.64:81 I need to send data to the socket from a web page using this javascript: window.o

Solution 1:

The following functions use the connection variable, but the variable is out of scope, because connection is defined using the var (local) keyword:

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

Either define `connection as a global value:

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

Or use an internal binding / reference:

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

Otherwise initialize connection as a global and assign onload like this:

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

Post a Comment for "Websocket Returns Undefined In Code But Not In Console"