A library to make working with websockets easier.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. var WSServer = require("ws").Server;
  2. var events = require("events");
  3. var util = require("util");
  4. //Request {
  5. function Request(sock, url, data, requestId) {
  6. this.data = data;
  7. this.url = url;
  8. this._sock = sock;
  9. this._requestId = requestId;
  10. this._replied = false;
  11. }
  12. Request.prototype.reply = function(data) {
  13. if (this._replied)
  14. throw new Error("Already replied.");
  15. this._sock._send({
  16. r: this._requestId,
  17. d: data
  18. });
  19. this._replied = true;
  20. }
  21. Request.prototype.fail = function(msg) {
  22. if (this._replied)
  23. throw new Error("Already replied.");
  24. this._sock._send({
  25. r: this._requestId,
  26. err: msg
  27. });
  28. this._replied = true;
  29. }
  30. //}
  31. //Socket {
  32. function Socket(websock) {
  33. this._websock = websock;
  34. this._ready = false;
  35. websock.on("close", function() {
  36. this._ready = false;
  37. this.emit("close");
  38. }.bind(this));
  39. websock.on("ready", function() {
  40. this._ready = true;
  41. this.emit("ready");
  42. });
  43. websock.on("message", function(msg) {
  44. var obj;
  45. try {
  46. obj = JSON.parse(msg);
  47. } catch (err) {
  48. this.emit("error", err);
  49. }
  50. var req = new Request(this, obj.n, obj.d, obj.r);
  51. this.emit("request", req);
  52. }.bind(this));
  53. }
  54. util.inherits(Socket, events.EventEmitter);
  55. //Generic internal send function
  56. Socket.prototype._send = function(data) {
  57. if (this._ready)
  58. this._websock.send(JSON.stringify(data));
  59. }
  60. //Trigger event on the client
  61. Socket.prototype.send = function(name, data) {
  62. this._send({
  63. evt: name,
  64. d: data
  65. });
  66. }
  67. //}
  68. //module.exports {
  69. module.exports = function(options) {
  70. var wss = new WSServer(options);
  71. this.socks = [];
  72. wss.on("connection", function(websock) {
  73. var sock = new Socket(websock);
  74. this.socks.push(sock);
  75. var i = this.socks.length - 1;
  76. sock.on("close", function() {
  77. this.socks.splice(i, 1);
  78. }.bind(this));
  79. this.emit("connection", sock);
  80. }.bind(this));
  81. }
  82. util.inherits(module.exports, events.EventEmitter);
  83. //}