title: Emit Events To Socket.IO Not Working From Server
body: <p>i am trying to get a chat program to work using socket.io but it doesnt seem to work properly.</p>
  
  <p>i am using a Node.js server and it seems to be running properly. i think this may have something to do with emitting to rooms.</p>
  
  <p>the code i have on the client browser is:</p>
  
  <pre><code>&lt;script&gt;
  
     var socket = io("https://localhost:3000/userChat");
     socket.on('connect', function(){ 
       socket.emit('initialiseConnection', "user1");
     });
  
     socket.on('messageIn', function(msg){
       console.log(msg);
       $('#messages').append($('&lt;li&gt;').text(msg.message));
     });
  
  &lt;/script&gt;
  </code></pre>
  
  <p>so when the page loads, socket.io it connects to the server and emits the "initialiseConnection" event on the server with "user1". which is a new room specifically for that user.</p>
  
  <p>on the server, the code i have handling "initialiseConnection" is:</p>
  
  <pre><code>socket.on("initialiseConnection", function(username){
      socket.join(username);
      console.log(username + " has joined.");
  
      Message.find({recipient:username}, function (err, message){
         console.log("messages for "+username+": "+message.length);
         for (var x = 0; x &lt; message.length; x++){
           console.log(username+"'s message "+x);
           console.log(message[x]);
  
           socket.to(username).emit("messageIn", {"message":message[x]});
         }
      });
  });
  </code></pre>
  
  <p>this code as you can see, creates and joins a room with the same name as the username. the looks in the database for any messages, and tries to emit those messages to the user. i log the message. there is definately a message and the username in the "socket.to()" method is also correctly shown in the logs. but the "socket.on('messageIn')" on the client browser doesnt seem to be picking up the event.</p>
  
  <p>i have also tried putting:</p>
  
  <pre><code>setTimeout(function() {
    socket.to(username).emit("messageIn", {"message":"test message"});
  }, 5000);
  </code></pre>
  
  <p>immediately after the socket.join(), in case this was related to some backbround processing that needed to complete</p>
  
  <p>can anyone see where i may have gone wrong on this?</p>
  
  <p>Thanks.</p>
  
  <p>--EDIT 1--------------------------------------</p>
  
  <pre><code>var https = require('https');
  var express = require('express');
  var app = express();
  var server = https.createServer(https_options, app).listen(3000);
  var io = require('socket.io')(server);
  
  var userChat = io.of("/userChat");
  userChat.on('connection', function(socket){
    console.log('a user connected');
  
    socket.on("initialiseConnection", function(username){
       ...
    });
  
    socket.on('disconnect', function(){
      socket.leave(socket.room);
    });
  });
  </code></pre>