title: Emit event to websocket from http request handler
body: <p>Using <a href="https://github.com/websockets/ws" rel="nofollow noreferrer">ws for NodeJS</a>. </p>
  
  <pre><code>const wss = new WebSocket.Server({ port: 8001 });
  
  wss.on('connection', function connection(ws) {
    ws.on('message', function incoming(message) {
      console.log('received: %s', message);
    });
  
    ws.send('{"message":"something"}');
  });
  </code></pre>
  
  <p>Connection from the client works great. </p>
  
  <pre><code>var connection = new WebSocket('ws://localhost:8001');
  connection.onopen = function(){
      console.log("opened");   
      var msg = "client message";
      connection.send(msg);
  }
  </code></pre>
  
  <p>This is logged as expected by the <code>message</code> handler on the NodeJS server.</p>
  
  <p>I am then making a post request from another server to the endpoint <code>relay</code>, set up like this (this part of the NodeJS server running on express):</p>
  
  <pre><code>const app = express();
  app.post('/relay', (request, response) =&gt;{
      console.log("relay hit.");
      wss.emit('message', 'server message');
      console.log("test message sent probably");
      response.send({ result: 'OK', message: 'good hits' });
  });
  const server = http.createServer(app);
  server.listen(8000, () =&gt; console.log('Listening on http://localhost:8000'));
  </code></pre>
  
  <p>The calling application gets the good response. </p>
  
  <p>The problem is that <code>wss.emit</code> doesn't trigger the <code>on('message')</code> callback. <code>wss.send</code> throws a "not a function" error. I'm imagining this is a scope issue, but I'm not sure, and haven't been able to figure out what scope or object I would actually need if it is.</p>
  
  <p>How does one trigger an event for the WebSocket Server internally? The only place I can even find <code>emit</code> in the docs is <a href="https://github.com/websockets/ws#multiple-servers-sharing-a-single-https-server" rel="nofollow noreferrer">here</a> and it's not explained at all. </p>