Using Socket.IO in server side with socket.io-client

I use the socket.io in my app.js and configure it with express framework, now when I run the application both of application and socket.io will start and I can emit messages between client and app.js.

app.js (Server)

var express = require('express'),
    app = express(),
    http = require('http'),
    server = http.creatServer(app),
    socket = require('socket.io'),
    io = socket.listen(server);

server.listen(3000);    

io.sockets.on('connection', function(client){
    client.on('message', function(msg){
        io.sockets.emit('message', msg);
    });
});

Client:

<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
    var server = io.connect('http://127.0.0.1:3000');
    server.emit('message', 'Hello World');
</script>

But I want to use socket in other Controllers... I use "socket.io-client (https://npmjs.org/package/socket.io-client)", now I want to get messages that emitted from app.js to all sockets.

controller.js (Server)

var io = require('socket.io-client'),
    socket = io.connect('127.0.0.1', {
        port: 3000
    });

socket.on('connect', function(){
    console.log('CONNECTED!!');
    socket.on('message', function(msg){
        console.log("New message:", msg);
    });
});

It can't connect!

If you don't care who gets the messages, you can do a global broadcast from socket.io. That works inside controllers.

you are not using the client socket to emit. io is the socket.io instance not the client socket that connected.

in server

io.sockets.on('connection', function(client){
    client.on('message', function(msg){
      client.emit('message', msg);
  });
});

if you need to broadcast, then you can use the io instance

io.socket.sockets.emit('message', msg);