将事件从http请求处理程序发送到websocket

时间:2019-04-22 12:55:30

标签: node.js websocket

使用ws for NodeJS

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="testTable"  align="center">
  <thead>
    <tr style="color: #D2002E; background: #FFCC01; height:32px;">
      <td>Agents</td>
      <td>Select</td>
    </tr>
  </thead>
  <tbody id="table_body_Test">
  </tbody>
</table>
<button id="submitBtn" onclick="ActionData()">Next</button>

与客户端的连接效果很好。

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"}');
});

这由NodeJS服务器上的var connection = new WebSocket('ws://localhost:8001'); connection.onopen = function(){ console.log("opened"); var msg = "client message"; connection.send(msg); } 处理程序按预期记录。

然后,我从另一个服务器向端点message发出发布请求,设置如下(NodeJS服务器的这一部分在express上运行):

relay

正在调用的应用程序获得了良好的响应。

问题在于const app = express(); app.post('/relay', (request, response) =>{ 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, () => console.log('Listening on http://localhost:8000')); 不会触发wss.emit回调。 on('message')引发“不是函数”错误。我在想这是一个范围问题,但我不确定,也无法弄清楚如果需要的话,我实际需要什么范围或对象。

如何在内部触发WebSocket服务器的事件?我什至在文档中找不到wss.send的唯一地方是here,根本没有解释。

0 个答案:

没有答案