【问题标题】:Design choice using node.js and express and socket.io使用 node.js 和 express 和 socket.io 的设计选择
【发布时间】:2015-07-26 17:03:08
【问题描述】:

我想制作一个网络应用程序,每个用户都可以创建一个其他用户可以加入的聊天室。我想要一个管理房间的主节点服务器,每次用户创建一个新房间时,主服务器都应该启动一个新的聊天服务器,它应该管理房间。

我的问题是,如何让新服务器在 node.js 中启动以及如何管理它?

【问题讨论】:

    标签: node.js web socket.io server


    【解决方案1】:

    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 的乐趣!

    【讨论】:

    • 我已经在使用这个设计了,谢谢。我希望每个用户能够连接到任意数量的房间,每个房间都在一个新窗口中。
    • 您也可以使用 socket.io 的房间功能来做到这一点!但是您不能做的是知道消息来自哪个房间,而无需在消息中的数据结构中实际指定它。您遇到了什么阻碍您实现多个房间连接的情况?
    • 我担心恶意客户端可能会操纵消息来自的房间。所以我认为最好不要让客户随消息一起发送房间。
    • 没错,我建议服务器确保用户每次可以将消息发送到房间。客户端只需对服务器执行类似socket.emit('msg', {room:room_id, msg:'Hello World'} 的操作。然后服务器将根据用户加入的房间向房间广播或不向房间广播消息。从我的角度来看,这似乎是一个可以接受的解决方案。即使客户猜到了一个他不能加入的room_id,他也无法加入。
    • 好吧,我一定会使用你的解决方案。谢谢。
    猜你喜欢
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    相关资源
    最近更新 更多