简体   繁体   中英

Design choice using node.js and express and socket.io

I want to make a web app where every user can create a chat room that other users can join. I would like to have a main node server managing the rooms, and every time a user creates a new room, a new chat server should be started by the main server and it should manage the room.

My question is, how can I make the new server start in node.js and how can I manage it?

Socket.io allows you too use the room feature and have the behavior you want (separate chat rooms) without running a separate chat server. Running a separate chat server is not really convenient in node.js because it means running another process, and it makes communication between the main server and the chat servers extra complicated.

What i would advise is using that feature and adopt the following kind of design:

io.on('connection', function(socket) {    
    //initialize the object representing the client
    //Your client has not joined a room yet
    socket.on('create_room', function(msg) {
        //initalize the object representing the room
        //Make the client effectively join that room, using socket.join(room_id)
    }
    socket.on('join_room', function(msg) {
        //If the client is currently in a room, leave it using socket.leave(room_id); I am assuming for the sake of simplicity that a user can only be in a single room at all time
        //Then join the new room using socket.join(room_id)
    }
    socket.on('chat_msg', function(msg) {
        //Check if the user is in a room
        //If so, send his msg to the room only using socket.broadcast.to(room_id); That way, every socket that have joined the room using socket.join(room_id) will get the message
    }
}

With this design, you're simply adding listeners to event, and once set up, the whole server is running fine without having to deal with concurrency or sub processes.

It's still very minimalist and you'll probably want to handle a few more concepts, such as unique nicknames, or password authentication etc. But that can easily be done using this design.

Have fun experimenting with socket.io and node.js!

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