命中 Express 端点后在 socket.io 中发出

Cam*_*ron 5 node.js express socket.io

我是套接字新手

我正在与使用 socket.io 的客户端一起运行快速网络服务器。

基本上,每当有人点击我的一个发布请求时,我都会向我的客户发出一个结果,表明该发布请求已被点击。我想象它看起来像这样。

节点服务器

const app = express();
app.post('/makeOrder', function(req, res){ 
   // Do some database logic that pushes the order into my database


   // This is where I'm stuck.
   // I want to notify the client that the order is placed.
   // Would it look something like this?
   io.in('kitchenSocket').emit('order-placed', 'An order has been placed!');


   // Last send something to finish the request
   res.send({test:"order placed"})
}
Run Code Online (Sandbox Code Playgroud)

网页客户端

<script src="/socket.io.js"></script>
<script>
    // What I currently have
    var socket = io.connect('http://localhost:5554/kitchenSocket');
    socket.on('order-placed', function (data) {
        alert("an order has been placed:" + data)
    });
</script>
Run Code Online (Sandbox Code Playgroud)

如何让它在被命中的快速端点上发出消息?

Luc*_*ren 1

这是一些我必须做的事情非常相似的代码,您需要添加一些更改,但这是一个一般想法。主要区别是我使用的是 Redis 服务器。如果这有帮助或者您有后续问题,请告诉我。

服务器端代码

 var io = require('socket.io').listen(app);
      var redis = require('socket.io-redis');
      io.adapter(redis({ host: config.redis, port:config.redisPort }));
      //sets allowed origions
      io.set("origins", "*:*");
      let sockectObj = [data to be sent]
      io.emit('notification', sockectObj);
Run Code Online (Sandbox Code Playgroud)

前端代码

this.socket = io(CONFIG.socket, { query: [naming parameter] });

this.socket.on("notification", function (resObj) {
  //Action to be performed
}.bind(this));
Run Code Online (Sandbox Code Playgroud)