각 채팅방에 대해 별도의 서버를 만드는 대신 동일한 서버에서 모든 서버를 실행하고 관련 채팅 소켓 이름에 대한 맵을 유지 관리 할 수 있습니다.
예를 들어
,
//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