Socket.IO未定义变量

Socket.IO undefiend variable

本文关键字:变量 未定义 IO Socket      更新时间:2023-09-26

我正在使用socket.io创建一个交互式图形应用程序。在服务器端有一个图形变量。当用户加载页面时,一个测试事件被发送到服务器,服务器设置变量并将其返回给用户。我有第二个节点拖动事件,但当我尝试拖动节点时,服务器会说图形的节点和链接变量是未定义的。

var express = require('express'),
    app = express(),
    http = require('http'),
    socketIo = require('socket.io');
var server = http.createServer(app),
    io = socketIo.listen(server);
var graph = {nodes : [], links : []}
server.listen(8080, function(){
  console.log('server is listening on localhost:8080');
});
app.use(express.static(__dirname + '/'));
io.on('connect', function(socket){
  // dump some test data
  socket.on('test', function(){
    // this just creates a few nodes in an array
    var data = { ... }    
    graph = data;
    io.emit('test', graph);
  });
  socket.on('eventNodeDragStart', function(index){
    console.log('event node drag start: ' + index);
    // undefiend, the graph.nodes is empty here
    console.log(graph.nodes[index] + "'n'n");
    // cannot read property of undefined 
    // also missing error handler on 'socket'
    if(graph.nodes[index].locked) return;
    graph.nodes[index].locked = true;
    io.emit('eventNodeDragStart', index);
  });
});

通过替换以下行解决了问题:

io.on('connect', function(socket){

这个:

io.sockets.on('connect', function(socket){

不知道为什么它有效,但它确实有效。