设计选择使用 node.js 并表达和 socket.io
Design choice using node.js and express and socket.io
我想制作一个网络应用程序,每个用户都可以创建一个其他用户可以加入的聊天室。我想要一个管理房间的主节点服务器,每次用户创建一个新房间时,主服务器应该启动一个新的聊天服务器来管理房间。
我的问题是,如何让新服务器在 node.js 中启动以及如何管理它?
Socket.io 允许您也使用房间功能并拥有您想要的行为(单独的聊天室),而无需 运行 单独的聊天服务器。 运行 一个单独的聊天服务器在 node.js 中并不是很方便,因为它意味着 运行 另一个进程,并且它使主服务器和聊天服务器之间的通信变得格外复杂。
我建议使用该功能并采用以下设计:
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
}
}
通过这种设计,您只需向事件添加侦听器,一旦设置完毕,整个服务器 运行 就可以了,无需处理并发或子进程。
它仍然非常简约,您可能想要处理更多概念,例如唯一昵称或密码验证等。
但是使用这种设计可以很容易地做到这一点。
尽情体验 socket.io 和 node.js!
我想制作一个网络应用程序,每个用户都可以创建一个其他用户可以加入的聊天室。我想要一个管理房间的主节点服务器,每次用户创建一个新房间时,主服务器应该启动一个新的聊天服务器来管理房间。
我的问题是,如何让新服务器在 node.js 中启动以及如何管理它?
Socket.io 允许您也使用房间功能并拥有您想要的行为(单独的聊天室),而无需 运行 单独的聊天服务器。 运行 一个单独的聊天服务器在 node.js 中并不是很方便,因为它意味着 运行 另一个进程,并且它使主服务器和聊天服务器之间的通信变得格外复杂。
我建议使用该功能并采用以下设计:
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
}
}
通过这种设计,您只需向事件添加侦听器,一旦设置完毕,整个服务器 运行 就可以了,无需处理并发或子进程。
它仍然非常简约,您可能想要处理更多概念,例如唯一昵称或密码验证等。 但是使用这种设计可以很容易地做到这一点。
尽情体验 socket.io 和 node.js!