1

I'm looking to send data to my node via a query string, and then have it parse the query and act accordingly.

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url');

app.listen( 61337 );

function handler( request, response ) {
  var requestURL = url.parse(request.url, true);

  if( requestURL.query.message ) {
        var data = JSON.parse( decodeURI( requestURL.query.message ) );
        pushMe( data );
    }

  /** ... */
}

function pushMe( data ) {
    io.sockets.socket( data.socketid ).emit( data.action, data.value );
}

io.sockets.on('connection', function( socket ) {
  socket.on('join', function( data ) {
    /** ... */
  });

  socket.on('disconnect', function() {
    /** ... */
  });
});

How ever my pushMe function returns an error: TypeError: Object has no method 'emit'

How can I emit data from my function?

c0nfus3d
  • 1,403
  • 3
  • 13
  • 25
  • Is `io.sockets.socket` a function? You're trying to call it. If it's an object, you want square brackets, like `io.sockets.socket[data.socketid]` – apsillers Sep 05 '14 at 16:14
  • apparently it's nothing, with the square brackets I get "Cannot read property of undefined" – c0nfus3d Sep 05 '14 at 17:15
  • 1
    Ah, are you using socket.io 1.0? They've changed the API considerably. Perhaps [Sending a message to a client via its socket.id](http://stackoverflow.com/questions/8467784/sending-a-message-to-a-client-via-its-socket-id) would be helpful? – apsillers Sep 05 '14 at 17:18
  • I figured it out! I saved the entire socket to a variable in an array. Will post solution. Thanks! :) – c0nfus3d Sep 06 '14 at 00:02

1 Answers1

1

I needed to save the entire socket to an array, and then access it that way...

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
url = require('url');

app.listen( 61337 );

var registeredSockets = [];

function handler( request, response ) {
  var requestURL = url.parse(request.url, true);

  if( requestURL.query.message ) {
        var data = JSON.parse( decodeURI( requestURL.query.message ) );
        pushMe( data );
    }

  /** ... */
}

function pushMe( data ) {
    registeredSockets[data.socketid].emit( data.action, data.value );
}

io.sockets.on('connection', function( socket ) {
  socket.on('join', function( data ) {
    registeredSockets[socket.id] = socket;
    /** ... */
  });

  socket.on('disconnect', function() {
    /** ... */
  });
});
c0nfus3d
  • 1,403
  • 3
  • 13
  • 25