AriesDevil AriesDevil - 1 year ago 47
Node.js Question

io.of('namespace').emit('event', message) not working with namespace in

I have an app like this following:

io.of('/hello').on('connection', function(socket) {
socket.emit('world', {});
});'/', function *(next) {
console.log("At here......");
var pushMessage = (yield parse.json(this));
if(flag !== 0) {
// io.of('/hello/').emit('world', pushMessage);
io.sockets.emit('world', pushMessage);
} else {
console.log("Do Nothing");

It receive a http request and emit an event. When I use io.sockets.emit it works well but when I specify a namespace with 'io.of('hello').emit' it doesn't work,why?

My client side is this:

var socket = io.connect('http://localhost:3000', {
'reconnection delay': 100,
'reconnection limit': 100,
'max reconnection attempts': 10
//server side use io.sockets.emit
socket.on('world', function(data) {

//if server side use io.of('/hello/').emit
//socket.of('/hello/').on('world', function(data) {
// alert(data.a);

Answer Source

Your code is more or less fine, but you are on different namespaces.

io.sockets.emit() broadcasts to everybody currently connected to your server via socket. That's the reason it works. Technically it's because that's a 'shortcut' for io.of('').emit() ('' being the namespace).

Assuming you're going to use the /hello namespace, this is what you have to do on your client:

var socket = io.connect('http://localhost:3000/hello'); // your namespace is /hello

on the server you first have to listen for connections on that namespace:

io.of('/hello').on('connection', function(socket) {
  socket.emit('world', { a: 'hi world' });



You may want to look at these: How to use and rooms on GitHub

### UPDATE ###

I conducted a little test:


$('document').ready(function() {
  var socket = io.connect("localhost:3000/hello");

  socket.on('hello', function() {
    console.log('hello received');

  var data = {};
  data.title = "title";
  data.message = "message";

  setTimeout(function() {
      type: 'POST',
      data: JSON.stringify(data),
      contentType: 'application/json',
      url: 'http://localhost:3000/hello',
      success: function(data) {
   }, 2000);


io.of('/hello').on('connection', function() {
  console.log("client connected");
});'/hello', function(req, res) {

... and it worked. I copied the jquery-ajax code from here.