简体   繁体   中英

Send messages from server (Expressjs routing) to client

I want to send messages from the server to the client and implement this in routes/index.js of my mean stack project. Does anyone know how to use socket.io here?:

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

PS: Previously, I have used socket.io one time in the project: the client opens a socket, and then the server emits a message named id , the client receives it. In the client:

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

In www (server):

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

But I cannot imagine how to write socket.emit inside Expressjs routing...

Edit 1: I tried to do the following to send a message to all the clients but in the console, it only displayed until before emit , and in the client it showed 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");
});

Actually my question comes down to a common question: how to use socket.io inside an express routes file.

And I have found a super answer: https://stackoverflow.com/a/31277123/702977

So in www :

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

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

If I want to send a message to a certain client, I need to pass the information like id as a parameter into router.post, and then use for example io.to(req.body.id).emit("message", req.body.message);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM