notification.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // 向游戏服发货
  2. var http = require('http');
  3. var events = require('events');
  4. var util = require('util');
  5. var Notification = function() {
  6. this.emitter = new events.EventEmitter(this);
  7. }
  8. Notification.prototype.send = function(
  9. host, // 游戏服主机信息(ip, port, name)
  10. orderId, // 订单id
  11. userName, // 用户名
  12. playerId, // 角色id
  13. cfid) { // 产品包的配置id
  14. var content = JSON.stringify({
  15. orderid:orderId,
  16. username:userName,
  17. playerid:playerId,
  18. rmb:cfid
  19. });
  20. var options = {
  21. method: "POST",
  22. host: host.ip,
  23. port: host.port,
  24. path: "/pay",
  25. headers: {
  26. "Content-Type": 'application/json',
  27. "Content-Length": content.length
  28. }
  29. };
  30. var emitter = this.emitter
  31. var req = http.request(options, function (res){
  32. if (res.statusCode == 200) {
  33. var bytes = [];
  34. var size = 0;
  35. res.on('data', function (data){
  36. bytes.push(data);
  37. size += data.length;
  38. });
  39. res.on('end', function (){
  40. var buf = Buffer.concat(datas, size);
  41. var json = JSON.parse(buf.toString());
  42. var errno = json.erron
  43. if (parseInt(errno)==0){
  44. emitter.emit('end', orderid)
  45. } else {
  46. var message = util.format("%s 拒绝发货(%s)", host.name, errno)
  47. emitter.emit('error', new Error(message))
  48. }
  49. });
  50. res.on('error', function (err){
  51. // Recv error
  52. emitter.emit('error', err)
  53. });
  54. }
  55. }).on('error', function(err){
  56. // Request error
  57. emitter.emit('error', err)
  58. });
  59. // send the request content
  60. req.write(content);
  61. req.end();
  62. return this
  63. }
  64. Notification.prototype.on = function(eventName, callback) {
  65. this.emitter.on(eventName, callback);
  66. return this
  67. }
  68. util.inherits(Notification, events.EventEmitter); //继承
  69. module.exports = Notification