我有一个带有函数的类,我希望将其分配给dgram obj的事件。
tdback
我试过了:
我猜这很简单,我只是很难......我如何将该函数分配给该事件处理程序?
编辑 - 完整模块
MessageServer.prototype.OnBind = function (datagram) {
var address = datagram.address();
console.log("server listening " + address.address + ":" + address.port);
};
datagram.on("listening",
function() {
OnBind(this);
});
答案 0 :(得分:4)
您的代码有几个问题,请使用文档作为参考清理一下。
见这里:https://nodejs.org/api/dgram.html
完全脱下袖口,未经测试过。但它应该让你知道从哪里开始我想。
MessageServer
这里是一个类,在它的方法中实现你的逻辑。然后实例化它并调用Bind
启动它
(这个界面可能还有一些改进空间)
var myMessageServer = new MessageServer('MyServer', 8888, new MessageQueue(), etc...);
myMessageServer.Bind();
-
var Dgram = require("dgram");
var Message = require("./Message");
function MessageServer(name, listenPort, messageQueue, bindCallBack, messageReceiveCallBack, closeCallback, errorCallback) {
this.name = name;
this.messageQueue = messageQueue;
this.port = listenPort;
this.server = Dgram.createSocket("udp4");
this.server.on("listening", this.OnBind.bind(this));
this.server.on("message", this.OnReceive.bind(this));
this.server.on("error", function (err) {
console.log(this.name + " error: " + error);
this.server.close();
}.bind(this));
this.server.on("close", function () {
console.log("server closing: " + name);
});
}
MessageServer.prototype.Bind = function () {
this.server.bind(this.port);
};
MessageServer.prototype.OnReceive = function (message, info) {
var msg = new Message(message, info.address, info.port);
this.messageQueue.Add(msg);
};
MessageServer.prototype.OnBind = function () {
var address = this.server.address();
console.log("server listening " + address.address + ":" + address.port);
};
module.exports = MessageServer;