WebSocket 在代码中返回未定义,但在控制台中没有返回。
2018-10-02
5584
我很难理解这里发生了什么...
我在 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个回答
以下函数使用
connection
变量,但该变量超出范围,因为
connection
是使用
var
(local)关键字定义的:
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);
否则,将 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);
};};
Myst
2018-10-02