Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Pass data from a Node.js server to a socket.io app

Pass data from a Node.js server to a socket.io app

Problem

I have this very simple app:

// Require HTTP module (to start server) and Socket.IO
var http = require('http'), 
    io = require('socket.io'),
    url  = require('url');

var server = http.createServer(function(req, res){ 
  req.on('data', function(data){
    console.log('Received Data');
  })
});
server.listen(3000);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 

  server.on('data',function(event){ 
     client.send(url.search);
     console.log('Received Data from socket app');
  });

  client.on('disconnect',function(){
    console.log('Server has disconnected');
  });

});

I need to curl the node Server to pass it some post data, then i would like this data to be handed to the socket.io app so that it can feed back to the currently connected clients.

Is there anyway to accomplish that ?

Many thanks,

Problem courtesy of: silkAdmin

Solution

The socket that you get from

var socket = io.listen(server);

you can always call emit on this to send a message to all connected clients. So in your http server, you can emit the posted data:

var server = http.createServer(function(req, res){ 
  var body = '';
  req.on('data', function(data){
    console.log('Received Data');
    body += data;
  });
  req.on('end', function() {
    // Emit the data to all clients
    socket.emit('foo message', body);
  });
});
Solution courtesy of: Linus Gustav Larsson Thiel

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Pass data from a Node.js server to a socket.io app

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×