Socket.io:如何从服务器到服务器以及向客户端发送消息?

时间:2020-03-15 14:59:41

标签: node.js socket.io

io在Node.Js应用程序的app.js中初始化。并且可以很好地将消息从用户发送到服务器/用户,但是我不明白如何从服务器到服务器(在应用程序内)或从服务器到用户(基于特定事件)发送消息。

这是我的app.js(带有socket.io的部分):

var app = express()
var http = require('http')
var server = http.Server(app)
var io = require('socket.io')(server)

io.on('connection', function(socket) {

    socket.on('disconnect', function(data) {

        // Notify the other person in the chat room
        // that his partner has left
        socket.broadcast.to(socket.room).emit('leave', {
            boolean: true,
            people: people_remaining,
        })
    })


    socket.on('chat message', function(msg) {
        console.log('message: ' + msg)
        io.sockets.in(socket.room).emit('chat message', msg)
        // io.emit('chat message', msg);
    })


    socket.on('login', function(data) {

        socket.username = data.user
        socket.room = data.id

        // Add the client to the room
        socket.join(data.id)

        // Send the startChat event to all the people in the
        // room, along with a list of people that are in it.

        socket.to(data.id).emit('startChat', {
            boolean: true,
            id: data.id,
        })
    })
})


假设我想这样做,以防服务器端发生特定事件,将事件chat-message发送到特定房间。

我该怎么做?

我必须将io设置为全局吗?我对此感到茫然...

例如,在import.js中:

if (param) {

    io.sockets.in(socket.room).emit('chat message', param)

}

但是,如果它在io中,那么它将如何知道我指的是哪个app.js

0 个答案:

没有答案