A library to make working with websockets easier.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.error = 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. websock.on("close", function() {
  35. this.emit("close");
  36. }.bind(this));
  37. websock.on("message", function(msg) {
  38. var obj;
  39. try {
  40. obj = JSON.parse(msg);
  41. } catch (err) {
  42. this.emit("error", err);
  43. }
  44. var req = new Request(this, obj.n, obj.d, obj.r);
  45. this.emit("request", req);
  46. }.bind(this));
  47. }
  48. util.inherits(Socket, events.EventEmitter);
  49. //Generic internal send function
  50. Socket.prototype._send = function(data) {
  51. this._websock.send(JSON.stringify(data));
  52. }
  53. //Trigger event on the client
  54. Socket.prototype.send = function(name, data) {
  55. this._send({
  56. evt: name,
  57. d: data
  58. });
  59. }
  60. //}
  61. //module.exports {
  62. module.exports = function(options) {
  63. var wss = new WSServer(options);
  64. this.socks = [];
  65. wss.on("connection", function(websock) {
  66. var sock = new Socket(websock);
  67. this.socks.push(sock);
  68. var i = this.socks.length - 1;
  69. sock.on("close", function() {
  70. this.socks.splice(i, 1);
  71. }.bind(this));
  72. this.emit("connection", sock);
  73. }.bind(this));
  74. }
  75. util.inherits(module.exports, events.EventEmitter);
  76. //}