【问题标题】:Send messages from server (Expressjs routing) to client从服务器(Expressjs 路由)向客户端发送消息
【发布时间】:2017-11-28 12:22:11
【问题描述】:

我想从服务器向客户端发送消息并在我的平均堆栈项目的routes/index.js 中实现这一点。有谁知道如何在这里使用socket.io?:

router.post('/message/sendMessage', function (req, res, next) {
    console.log("router.post /message/sendMessage " + req.body)
    // send req.body to client
});

PS: 之前我在项目中使用过一次socket.io:客户端打开一个socket,然后服务端发出一个名为id的消息,客户端接收到。在客户端:

socket = io.connect();
socket.on('id', function (id) { ... })

www(服务器):

io.sockets.on('connection', function (socket) {
  console.log("LOG: just connected: " + socket.id);
  socket.emit('id', socket.id);
  socket.on('disconnect', function () {
    console.log("LOG: just disconnected: " + socket.id)
  })
})

但我无法想象如何在 Expressjs 路由中写 socket.emit...

编辑1:我尝试执行以下操作向所有客户端发送消息,但在控制台中,它只显示到before emit,而在客户端显示Failed to load resource: the server responded with a status of 500 (Internal Server Error)

router.post('/message/sendMessage', function (req, res, next) {
    console.log("router.post /message/sendMessage");
    console.log("before emit");
    io.sockets.on('connection', function (socket) {
        console.log("LOG: just connected: " + socket.id);
        io.emit("message", "this is a test");
        socket.on('disconnect', function () {
            console.log("LOG: just disconnected: " + socket.id)
        })
    })
    console.log("after emit");
});

【问题讨论】:

  • 你的 http 连接有会话对象吗?如果是这样,您可以在 socket.io connect 第一次连接时将socket.id 放入会话中,然后您可以从任何http请求的会话对象中获取socket.id,并使用socket.id,您可以获得然后您可以将其连接到socket.emit() 的套接字。
  • 假设我可以将 id 传递给 http 请求,我怎样才能从 id 中获取套接字?
  • 正如我之前问过的,您是否已经为 http 连接建立了快速会话?如果是这样,有一些模块可以帮助您在 http 和 socket.io 套接字之间进行互连。请回答您是否已经建立了会话?

标签: javascript express npm websocket socket.io


【解决方案1】:

其实我的问题归结为一个常见问题:如何在 express 路由文件中使用 socket.io。

我找到了一个超级答案:https://stackoverflow.com/a/31277123/702977

所以在www:

var io = require('socket.io').listen(server);
app.set('socketio', io);

index.js:

router.post('/message/sendMessage', function (req, res, next) {
    console.log("router.post /message/sendMessage");
    var io = req.app.get('socketio');
    io.emit("message", "hi!");
    res.json("hahaha")
});

如果我想向某个客户端发送消息,我需要将id之类的信息作为参数传递给router.post,然后使用例如io.to(req.body.id).emit("message", req.body.message);

【讨论】:

  • io.emit() 发送给所有连接的客户端,而不仅仅是发出 http 请求的客户端。
猜你喜欢
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 2015-01-05
  • 2017-07-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多