0

我有一些代码应该监听某些事件并处理它们,但要么这些事件实际上从未发出,要么监听器永远不会捕获它们。

这里有两个模块:监听的服务器和处理的应用程序(应用程序是主模块)。

server.js:

var events = require('events'),
    util   = require('util'),
    dgram  = require('dgram');

var Server = function() {
    this.self = this;
    events.EventEmitter.call(this);

    this.socket = dgram.createSocket('udp4');
    this.init = function(port) {
        this.socket.bind(port);
        console.log('Listening on port ' + port);
    }

    this.socket.on('message', function(buf, rinfo) {
        var rawInfo = buf.toString().split('&');
        var data = {};

        for (var i = 0; i < rawInfo.length; i++) {
            var key = rawInfo[i].split('=')[0];
            var val = rawInfo[i].split('=')[1];
            data[key] = val;
        }

        var type = data.type;

        console.log('emitting event type ' + type);
        this.emit(type, data);
    });
};

util.inherits(Server, events.EventEmitter);

// exports
module.exports = Server;

(这是唯一可能创建的对象):

{   type: 'login',
    name: 'x3chaos',
    displayname: 'x3chaos',
    world: 'world' }

应用程序.js:

var dgram  = require('dgram');
var Server = require('./server');

var server = new Server();
server.init(41234);

// FIXME
server.on('login', function(data) {
    console.log('received data');
    console.log(data);
});

这里有什么问题:事件没有触发还是听众没有听?
它也可能只是我想念的东西。你知道他们怎么说两个头...

蒂亚:)

4

1 回答 1

1

I think that this.emit wont work because you're in a callback, and this wont refer to the Server instance but to the callback context. Upthere, instead of this.self=this try to do var self=this and then inside the callback do self.emit...

于 2013-03-08T23:42:13.793 回答