Hosting multiple instances of a node.js server

637 Views Asked by At

I'm new to node.js and I'm working on learning how to use Socket.io to create multiple chat servers on my domain.

Here's the scenario:

  • you log onto the site
  • you pick a chat room or create a chat room
  • you join that individual chat room while other chat rooms are going on at the same time

Pretty standard operation on the web but I have yet to find a way to do it. Specifically, how to host it on your domain.

When creating and testing I always just use my localhost and tell the server to listen(8000) . However, how do write a script that:

A) creates a new listening port dynamically for each new chat sever?

B) how do I host it (I use Hostmonster)?

1

There are 1 best solutions below

1
On

Instead of creating a separate server for each chat room, you could run all of them from the same server and just maintain a map of chat room name to the sockets involved in it.

For example,

//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 } );
          });
        });
      });
    });   
  });
});

Note, this code is untested and is just an idea (you should probably treat it more like pseudocode). There are a bunch of things it doesn't handle like cleanup upon disconnects, errors, etc. There are probably lots of other (and better) ways to accomplish this too but hopefully it'll give you some more ideas.