title: Send message synchronously with Nodejs Websocket
body: <p>My app has three modules:</p>
  
  <ol>
  <li>WebSocket Module: resides on the remote server (internet) and it acts as a Websocket
  server that entertain the connection between Client Module and
  Webhook module. </li>
  <li>Webhook Module: resides on the remote server (internet) and it acts as
  a webhook to answer the HTTP post request from the user. It is connected to Websocket Module via websocket as well. </li>
  <li>Client Module: resides on my local machine and it is connected to
  the
      Webhook model via websocket. This client responsible to get query
      from my local backend.</li>
  </ol>
  
  <p>When a user call Webhook Module through HTTP Post request, Webhook module initiate a connection to WebSocket module via websocket. Then, the WebSocket module initiate the connection to Client module and response back with the necessary information. Actually I have to do this to eliminate the HTTP tunnel that is blocked in my company.</p>
  
  <p>The problem is, when I open two browser windows to perform the HTTP Post request <strong><em>at the same time</em></strong> with different parameter, for example, param "A", I would expect to get return "A", with param "B", I expect to get "B" not "A". But There is something wrong with my codes/design. If I executed at the same time, I throw "A" then I got "B" which is wrong. How do I overcome this.</p>
  
  <p>This is a simple diagram to illustrate it.
  <a href="https://i.stack.imgur.com/VUva0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VUva0.jpg" alt="enter image description here"></a></p>
  
  <p><strong>WebSocket Module</strong>:</p>
  
  <pre><code>'use strict'
  
  //This is WebSocket Server
  
  const clients = {};
  const SocketIO = require('socket.io');
  const express = require('express');
  const http = require('http');
  const app = express();
  const server = http.createServer(app);
  const ws = SocketIO(server);
  
  const port = 3000;
  
  var clientid;
  
  ws.on('connection', (client) =&gt; {
    clients[client.id] = client;
    console.log('new connection', client.id);
  
    clientid = client.id;
  
    client.emit('message', { message: 'welc' })
  
    client.on('disconnect', () =&gt; {
      delete clients[client.id];
      console.log('Client ' + client.id + ' disconnected. Deleted');
    });
  
    client.on('WH', function (from, msg) {
      console.log('Message from Webhook', from, ' : ', msg);
      client.broadcast.emit('message', { message: msg });
  
      //console.log('send to: ' + clientid);
      //ws.to(clientid).emit('hey', { message: msg });
  
      //client.emit('message', { message: msg })
    });
  
    client.on('CL', function (from, msg) {
      console.log('Message from Client', from, ' : ', msg);
      client.broadcast.emit('message', 'me', msg);
  
      //ws.to(client.id).emit('message', 'me', msg);
      //client.emit('message', 'me', msg);
    });
  
  
  });
  server.listen(process.env.PORT || port);
  console.log('WebSocket Server is running on port ' + port);
  </code></pre>
  
  <p><strong>Webhook Module</strong></p>
  
  <pre><code>'use strict'
  
  //This is WebHook Server
  
  const express = require('express');
  const bodyParser = require('body-parser');
  const request = require('request');
  const http = require('http');
  const io = require('socket.io-client');
  
  const app = express()
  app.use(bodyParser.json())
  
  const clients = {};
  const SocketIO = require('socket.io');
  const server = http.createServer(app);
  const ws = SocketIO(server);
  
  const port = 5000;
  
  let Res;
  let httpreq = false;
  let nctid;
  let ts;
  
  const socket = io.connect('http://localhost:3000', {reconnect: true});
  
  // Add a connect listener
  socket.on('connect', function() {
      console.log('Connected to WebSocket server!');
  });
  
  
  socket.on('message', function(from, msg) {
  
      //console.log('Message from ', from, ' : ', msg);
      console.log('nctid: ' + nctid + ', ts: ' + ts);
  
      //Get the message from Client
  
      if (httpreq) {
          Res.send({
              replies: [{
                  type: 'text',
                  content: msg,
              }],
              conversation: {
                  memory: {
                      key: msg
                  }
              }
          })
  
          httpreq = false;
      }
  });
  
  app.listen(process.env.PORT || port, () =&gt; {
      console.log('Webhook server is running on port ' + port);
  })
  
  
  app.post('/', (req, res) =&gt; {
      //console.log(req.body)
  
      let query = req.body.nlp.entities.query[0].value;
      nctid = req.body.nlp.entities.nctid[0].value;
  
      ts =  Math.floor(Date.now() / 1000);
  
      console.log("query: " + query + '|' + nctid + '|' + ts);
  
      //Send message to WebSocket server with parameter query and NCTID
  
      socket.emit('WH', 'me', query + '|' + nctid);
      Res = res;
      httpreq = true;
  })
  
  app.post('/errors', (req, res) =&gt; {
      console.log(req.body);
      res.send();
  })
  </code></pre>
  
  <p><strong>Client Module</strong></p>
  
  <pre><code>'use strict'
  
  //This is client app running on client premise
  
  const request = require('request');
  const parser = require('xml2json');
  const io = require('socket.io-client');
  const socket = io.connect('http://localhost:3000', {reconnect: true});
  
  // Add a connect listener
  socket.on('connect', function(socket) {
      console.log('Connected to WebSocket server!');
  });
  
  socket.on('message', function(from, msg) {
      //console.log('MSG', from, ' : ', msg);
      console.log(from);
      let param = from.message.split('|');
      let query = param[0];
      let nctid = param[1];
  
  
      if (typeof nctid != 'undefined') {
          getNCTID(nctid, function(returnValue) {
              //console.log(returnValue);
              try {
                  let json = parser.toJson(returnValue);
                  json = JSON.parse(json);
  
                  if (query == 'title')
                      socket.emit('CL', 'me', 'Title is ' + json.clinical_study.brief_title);
                  else
                      socket.emit('CL', 'me', 'Status is ' + json.clinical_study.overall_status);
  
              } catch (e) {
                  console.log(e);
                  socket.emit('CL', 'me', 'No NCTID ' + nctid);
              }
          });
      }
  });
  
  
  function getNCTID(nctid, callback) {
  
      let url = "https://clinicaltrials.gov/ct2/show/" + nctid + "?displayxml=true";
  
      let options = {
          url: url,
          method: 'GET'
      }
  
      //console.log(options);
      let requestWithEncoding = function(options, callback) {
          let req = request.get(options);
  
          req.on('response', function(res) {
              let chunks = [];
              res.on('data', function(chunk) {
                  chunks.push(chunk);
              });
  
  
              res.on('end', function() {
                  let buffer = Buffer.concat(chunks);
                  let encoding = res.headers['content-encoding'];
                  if (encoding == 'gzip') {
                      zlib.gunzip(buffer, function(err, decoded) {
                          callback(err, decoded &amp;&amp; decoded.toString());
                      });
                  } else if (encoding == 'deflate') {
                      zlib.inflate(buffer, function(err, decoded) {
                          callback(err, decoded &amp;&amp; decoded.toString());
                      })
                  } else {
                      callback(null, buffer.toString());
                  }
              });
          });
  
  
          req.on('error', function(err) {
              callback(err);
          });
      }
  
  
      requestWithEncoding(options, function(err, data) {
          if (err) {
              console.log('err:' + err);
              callback('error');
          } else
              //console.log(data);
              callback(data);
      })
  }
  </code></pre>