簡體   English   中英

使用node.js和express和socket.io進行設計選擇

[英]Design choice using node.js and express and socket.io

我想制作一個Web應用程序,每個用戶都可以創建一個聊天室,其他用戶可以加入該聊天室。 我希望有一個主節點服務器來管理會議室,並且每當用戶創建一個新會議室時,主服務器應啟動一個新的聊天服務器,並由它來管理會議室。

我的問題是,如何使新服務器在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玩得開心!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM