Home Reference Source

src/MessageHandler/Client/index.js

  1. const zmq = require('zeromq');
  2. const config = require('./../../config');
  3. const logger = require('./../../Logger');
  4.  
  5. let qSock = null;
  6.  
  7. /**
  8. * Messaging Class for the Client component.
  9. */
  10. class MessageClient {
  11.  
  12. /**
  13. * Constructor for the MessageServer.
  14. * @property {object} sock Defines the router socket that represents the type of communication that can be handled.
  15. */
  16. constructor() {
  17. /** Describes the kind of socket. In this case a dealer socket. */
  18. this.sock = zmq.socket('dealer');
  19. this.sock.identity = config.identity;
  20. this.sock.connect(`tcp://${config.app.backendIp}:${config.app.port}`);
  21. logger.info(`Message Client connected to port ${config.app.port}`);
  22. qSock = this.sock;
  23.  
  24. this.sendMessage('pong', this.sock.identity);
  25.  
  26. // can't convert to es6
  27. // listens to messages that are received on the socket.
  28. this.sock.on('message', function onMessage() {
  29. let args = Array.apply(null, arguments);
  30. let topic = args[0].toString('utf8');
  31.  
  32. if (topic == 'ping')
  33. qSock.send(['pong', '']);
  34.  
  35. logger.verbose(`[${Date.now()}]received a message related to:`, 'containing message:', args[1].toString('utf8'));
  36. });
  37. }
  38.  
  39. /**
  40. * Sends a message to the connected Router.
  41. * @param {string} topic Describes the context.
  42. * @param {string} message Actual message content.
  43. */
  44. sendMessage(topic, message) {
  45. logger.verbose(`Sending following message: ${this.sock.identity} - ${message}.`);
  46. this.sock.send([topic, message]);
  47. }
  48. }
  49.  
  50. module.exports = MessageClient