與其爲每個聊天室創建一個單獨的服務器,您可以從同一臺服務器運行所有這些服務器,並僅將聊天室名稱映射到其中涉及的套接字。
例如,
//store a map of chat room name to sockets here
var chatRooms = {};
io.sockets.on('connection', function (socket) {
//when someone wants to join a chat room, check to see if the chat room name already exists, create it if it doesn't, and add the socket to the chat room
socket.on('joinChatRoom', function (data.message) {
var chatRoomName = data.message;
chatRooms[chatRoomName] = chatRooms[chatRoomName] || [];
chatRooms[chatRoomName].push(socket);
//set the chatRoomName into the socket so we can access it later
socket.set("chatRoomName", chatRoomName, function() {
//when we receive a message
socket.on("chatMessage", function(data) {
var chatMessage = data.message;
//figure out what chat room this socket belongs to
socket.get("chatRoomName", function(err,chatRoomName) {
//iterate over the sockets in the chat room and send the message
chatRooms[chatRoomName].each(function(chatRoomSocket) {
chatRoomSocket.emit("chatMessage", { message : chatMessage });
});
});
});
});
});
});
注意,這個代碼是未經測試,只是一個想法(你應該把它更像是僞代碼)。有很多事情在斷開連接,錯誤等情況下無法處理。可能還有很多其他(或更好的)方法來完成此操作,但希望它能給您更多的想法。
是的人是一個偉大的開始。我有這樣的想法,可能是可行的,但它可能會造成一些頭痛。我會讓你知道它是如何展開的。 – JDillon522