使用node.js和express和socket.iodeviseselect

我想制作一个networking应用程序,每个用户都可以创build一个其他用户可以join的聊天室。 我想有一个主节点服务器pipe理房间,每当用户创build一个新的房间时,一个新的聊天服务器应该由主服务器启动,它应该pipe理房间。

我的问题是,如何使新的服务器在node.js中启动,我该如何pipe理它?

Socket.io还允许您使用房间function并拥有您想要的行为(单独的聊天室),而无需运行单独的聊天服务器。 在node.js中运行一个单独的聊天服务器并不方便,因为它意味着运行另一个进程,并且使主服务器和聊天服务器之间的通信更为复杂。

我会build议使用该function并采用以下types的devise:

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

通过这种devise,您只需将侦听器添加到事件中,一旦设置完成,整个服务器运行良好,而无需处理并发或subprocess。

它仍然是非常简约的,你可能会想要处理更多的概念,如独特的昵称,或密码authentication等,但这可以很容易地使用这种devise。

试试socket.io和node.js吧!