是否可以在Node.js中监听对象实例化? [英] Is it possible to listen for object instantiation in Node.js?

查看:41
本文介绍了是否可以在Node.js中监听对象实例化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Node.Js中开发一个浏览器游戏,并且我有这个脚本:

game.js >>

  var config = require('./game_config.js');var mysql = require('mysql');var app = require('express')();var http = require('http').Server(app);var io = require('socket.io')(http);var connexion = mysql.createConnection({'主机':config.DB_HOST,'用户':config.DB_USER,'密码':config.DB_PASS,'数据库':config.DB_NAME});var Player = require('./server/class.player.js');io.on('connect',function(socket){console.log('Co');var播放器socket.on('login',function(data){connexion.query("SELECT * FROM player WHERE nick ='" + data.login +'AND pass ='" + data.pass +'",function(err,rows){如果(错误){抛出错误;} 别的 {如果(rows.length == 0){var dataRet ="LOG";socket.emit('login',dataRet);} 别的 {var p = rows [0];var dataRet = new Player(p.id,p.nick,p.map_id,p.x,p.y,connexion).toJson();console.log(dataRet);}//如果没有setTimeout,它将无法正常工作,因为对象没有时间实例化setTimeout(function(){socket.emit('login',dataRet);},1000);}});});socket.on('disconnect',function(socket){console.log('Disco');});}); 

class.Player.js >>

  var Player =函数(id,名称,map_id,x,y,连接){this.id = id;this.name =名称;this.map_id = map_id;this.x = x;this.y = y;this.link =连接;this.toJson = function(){返回 {'id':this.id,'名称':this.name,'map_id':this.map_id,'x':this.x,'y':这.y};}}module.exports =用户; 

所以基本上,由于game.js中的"setTimeout()"(对于socket.emit()事件),我的代码可以正常工作.如果我不使用它,由于Node.js的异步性,对象"dataRet"没有时间实例化,因此套接字发出未定义"或空"的消息.

所以我在想,必须有一种侦听对象实例化的方法,以便在完成后立即通过socket.io发出它.

解决方案

警告:SQL注入漏洞

这本身与您的问题无关,但这很重要-您有大量的 SQL注入漏洞,任何人都可以对您的数据库做任何事情.

代替:

  connection.query(选择*从球员尼克='+ data.login +'AND pass ='" + data.pass +'",函数(错误,行){//...}); 

可以使用:

connection.escape(data.login) connection.escape(data.pass)代替 data.login data.pass

或:

  connection.query(选择*来自玩家的昵称nick =?AND pass =?",[data.login,data.pass],函数(错误,行){//...}); 

它不仅更安全,而且实际上更容易阅读和理解.请参阅:转义查询值./github.com/felixge/node-mysql#readme"rel =" nofollow noreferrer> node-mysql手册.

答案

现在,回到您的问题.关于Player构造函数,没有什么异步的,因此您的问题必须是其他问题.这里让我们感到奇怪的是,您的Player.js导出了 User (未定义)而不是 Player (已定义),所以我很惊讶它甚至可以正常工作.或者您可能发布了与实际使用的代码不同的代码,这可以解释为什么您的竞态条件在代码中并不明显.

但是,如果您的Player构造函数正在进行一些异步调用,那么我建议您添加一个回调参数并从构造函数中调用它:

  var Player =函数(id,名称,map_id,x,y,连接,回调){this.id = id;this.name =名称;this.map_id = map_id;this.x = x;this.y = y;this.link =连接;this.toJson = function(){返回 {'id':this.id,'名称':this.name,'map_id':this.map_id,'x':this.x,'y':这.y};}//您必须等待的一些异步调用//用setTimeout表示:setTimeout(function((){if(callback&& typeof callback ==='function'){回调(this);}},1000);} 

然后可以将回调传递给构造函数,因此:

 }其他{var p = rows [0];var dataRet = new Player(p.id,p.nick,p.map_id,p.x,p.y,connexion).toJson();console.log(dataRet);}//如果没有setTimeout,它将无法正常工作,因为对象没有时间实例化setTimeout(function(){socket.emit('login',dataRet);},1000); 

可以更改为以下内容:

 }其他{var p = rows [0];var dataRet = new Player(p.id,p.nick,p.map_id,p.x,p.y,connexion,function(){socket.emit('login',dataRet);}).toJson();console.log(dataRet);} 

但是在这里,正如我所说,没有什么是异步的,而且甚至在运行setTimeout之前,您的 dataRet 都已经设置好了,所以这不能解决您的问题,但可以回答您的问题.>

I am working on a browser-game in Node.Js and I have this script :

game.js >>

var config = require('./game_config.js');
var mysql = require('mysql');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var connexion = mysql.createConnection({
    'host': config.DB_HOST,
    'user' : config.DB_USER,
    'password' : config.DB_PASS,
    'database' : config.DB_NAME 
});
var Player = require('./server/class.player.js');

io.on('connect', function(socket) {
    console.log('Co');
    var player
    socket.on('login', function(data) {
        connexion.query("SELECT * FROM player WHERE nick = '"+data.login+"' AND pass = '"+data.pass+"'", function(err, rows) {
            if (err) {
                throw err;
            } else {
                if (rows.length == 0) {
                    var dataRet = "LOG";
                    socket.emit('login', dataRet);
                } else {
                    var p = rows[0];
                    var dataRet = new Player(p.id, p.nick, p.map_id, p.x, p.y, connexion).toJson();
                    console.log(dataRet);
                }
                // Without setTimeout it wouldn't work because the object didn't have the time to instantiate
                setTimeout(function() {
                    socket.emit('login', dataRet);
                },1000);
            }
        });
    });
    socket.on('disconnect', function(socket) {
        console.log('Disco');
    });
});

class.Player.js >>

var Player = function (id, name, map_id, x, y, connexion) {
    this.id = id;
    this.name = name;
    this.map_id = map_id ;
    this.x = x;
    this.y = y;
    this.link = connexion;
    this.toJson = function () {
        return {
            'id' : this.id,
            'name' : this.name,
            'map_id' : this.map_id,
            'x' : this.x,
            'y' : this.y
        };
    }
}

module.exports = User;

So basicly, my code works fine thanks to the "setTimeout()" in game.js (for the socket.emit() event). If I don't use it, the object 'dataRet' doesn't have the time to instantiate due to the asynchronousity of Node.js, so the socket emits "undefined" or "null".

So I was thinking, there MUST be a way to listen for an object instantiation in order to emit it through socket.io as soon as it's done.

解决方案

Warning: SQL Injection Vulnerability

This is not related your question per se but this is quite important - you have a huge SQL injection vulnerability and anyone can do anything to your database.

Instead of:

connection.query(
  "SELECT * FROM player WHERE nick = '"
  + data.login + "' AND pass = '" + data.pass + "'",
  function (err, rows) {
    //...
  }
);

either use:

connection.escape(data.login) and connection.escape(data.pass) in place of data.login and data.pass

or:

connection.query(
  "SELECT * FROM player WHERE nick = ? AND pass = ?", [data.login, data.pass],
  function (err, rows) {
    // ...
  }
);

It is not only safer but also actually much easier to read and understand. See: Escaping query values in node-mysql manual.

The Answer

Now, back to your question. There is nothing asynchronous about your Player constructor so your problem must be something else. What is strange here us that your Player.js exports User (that is not defined) and not Player (that is defined) so I'm surprised it even works at all. Or you maybe posted a different code than what you're actually using which would explain why you have a race condition that is not obvious from the code.

But if your Player constructor was making some asynchronous calls then I would suggest adding a callback argument and calling it from the constructor:

var Player = function (id, name, map_id, x, y, connexion, callback) {
    this.id = id;
    this.name = name;
    this.map_id = map_id ;
    this.x = x;
    this.y = y;
    this.link = connexion;
    this.toJson = function () {
        return {
            'id' : this.id,
            'name' : this.name,
            'map_id' : this.map_id,
            'x' : this.x,
            'y' : this.y
        };
    }

    // some async call that you have to wait for
    // symbolized with setTimeout:
    setTimeout(function () {
      if (callback && typeof callback === 'function') {
        callback(this);
      }
    }, 1000);
}

and then you can pass a callback to your constructor, so this:

          } else {
                var p = rows[0];
                var dataRet = new Player(p.id, p.nick, p.map_id, p.x, p.y, connexion).toJson();
                console.log(dataRet);
            }
            // Without setTimeout it wouldn't work because the object didn't have the time to instantiate
            setTimeout(function() {
                socket.emit('login', dataRet);
            },1000);

could change to something like:

          } else {
                var p = rows[0];
                var dataRet = new Player(p.id, p.nick, p.map_id, p.x, p.y, connexion, function () {
                    socket.emit('login', dataRet);
                }).toJson();
                console.log(dataRet);
            }

but here, as I said, nothing is asynchronous and also your dataRet is already set even before you run the setTimeout so this is not solving your problem, but it is answering your question.

这篇关于是否可以在Node.js中监听对象实例化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆