从服务器(Expressjs路由)向客户端发送消息

时间:2017-06-25 12:50:56

标签: javascript express npm websocket socket.io

我想从服务器向客户端发送消息,在我的平均堆栈项目的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次:客户端打开一个套接字,然后服务器发出一条名为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) 1}}

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

1 个答案:

答案 0 :(得分:1)

实际上我的问题归结为一个常见问题:如何在快速路由文件中使用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);