// 向游戏服发货 var http = require('http'); var events = require('events'); var util = require('util'); var Notification = function() { this.emitter = new events.EventEmitter(this); } Notification.prototype.send = function( host, // 游戏服主机信息(ip, port, name) orderId, // 订单id userName, // 用户名 playerId, // 角色id cfid) { // 产品包的配置id var content = JSON.stringify({ orderid:orderId, username:userName, playerid:playerId, rmb:cfid }); var options = { method: "POST", host: host.ip, port: host.port, path: "/pay", headers: { "Content-Type": 'application/json', "Content-Length": content.length } }; var emitter = this.emitter var req = http.request(options, function (res){ if (res.statusCode == 200) { var bytes = []; var size = 0; res.on('data', function (data){ bytes.push(data); size += data.length; }); res.on('end', function (){ var buf = Buffer.concat(datas, size); var json = JSON.parse(buf.toString()); var errno = json.erron if (parseInt(errno)==0){ emitter.emit('end', orderid) } else { var message = util.format("%s 拒绝发货(%s)", host.name, errno) emitter.emit('error', new Error(message)) } }); res.on('error', function (err){ // Recv error emitter.emit('error', err) }); } }).on('error', function(err){ // Request error emitter.emit('error', err) }); // send the request content req.write(content); req.end(); return this } Notification.prototype.on = function(eventName, callback) { this.emitter.on(eventName, callback); return this } util.inherits(Notification, events.EventEmitter); //继承 module.exports = Notification