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.6KB

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