EzDevInfo.com

socket.io interview questions

Top socket.io frequently asked interview questions

Get the client's IP address in socket.io

When using socket.IO in a Node.js server, is there an easy way to get the IP address of an incoming connection? I know you can get it from a standard HTTP connection, but socket.io is a bit of a different beast.


Source: (StackOverflow)

How to remove debugging from an Express app?

I would like to remove the debugging mode. I am using express, redis, socket.io and connect-redis, but I do not know where the debugging mode comes from.

Node debug

Someone has an idea?


Source: (StackOverflow)

Advertisements

Which websocket library to use with Node.js?

Currently there is a plethora of websocket libraries for node.js, the most popular seem to be:

However I can't find any solid concrete comparisons between any of them... Apparently Socket.io was awesome, but has become quite dated and has failing builds. Both ws and websocket-node claim they are the fastest. And engine.io seems new, but a lot heavier than the lighter aletarntives.

It would be amazing if we or someone could put together an answer that serves as a guide on which socket library to use and when, as well as a comparison between them.


Source: (StackOverflow)

Where is the socket.io client library?

As far as I have seen, there is no explanation as to where we are to locate the client side script for socket.io if node.js is not used as the web server. I've found a whole directory of client side files, but I need them in a combined version (like it's served when using node.js webs servers). Any ideas?


Source: (StackOverflow)

Faye vs. Socket.IO (and Juggernaut)

Socket.IO seems to be the most popular and active WebSocket emulation library. Juggernaut uses it to create a complete pub/sub system.

Faye is also popular and active, and has its own javascript library, making its complete functionality comparable to Juggernaut. Juggernaut uses node for its server, and Faye can use either node or rack. Juggernaut uses Redis for persistence (correction: it uses Redis for pub/sub), and Faye only keeps state in memory.

  1. Is everything above accurate?
  2. Faye says it implements Bayeux -- i think Juggernaut does not do this -- is that because Juggernaut is lower level (IE, I can implement Bayeux using Juggernaut)
  3. Could Faye switch to using the Socket.IO browser javascript library if it wanted to? Or do their javascript libraries do fundamentally different things?
  4. Are there any other architectural/design/philosophy differences between the projects?

Source: (StackOverflow)

Send message to specific client with socket.io and node.js

I'm working with socket.io and node.js and until now it seems pretty good, but I don't know how to send a message from the server to an specific client, something like this:

client.send(message, receiverSessionId)

But neither the .send() nor the .broadcast() methods seem to supply my need.

What I have found as a possible solution, is that the .broadcast() method accepts as a second parameter an array of SessionIds to which not send the message, so I could pass an array with all the SessionIds connected at that moment to the server, except the one I wish send the message, but I feel there must be a better solution.

Any ideas?


Source: (StackOverflow)

Whats the difference between io.sockets.emit and broadcast?

What's the difference between io.sockets.emit and socket.broadcast.emit? Is it only that broadcast emits to everyone BUT the socket that sends it?

It seems like they can be used interchangeably:

io.sockets.on('connection', function (socket) {
  //these should do the same thing  
  io.sockets.emit('this', { receivers: 'everyone'});

  socket.broadcast.emit('this', { receivers: 'everyone but socket'}); //emits to everyone but socket
  socket.emit('this', { receivers: 'socket'}); //emits to socket
});

Source: (StackOverflow)

socket.emit() vs. socket.send()

What's the difference between these two?

I noticed that if I changed from socket.emit to socket.send in a working program, the server failed to receive the message, although I don't understand why.

I also noticed that in my program if I changed from socket.emit to socket.send, the server receives a message, but it seems to receive it multiple times. When I use console.log() to see what the server received, it shows something different from when I use socket.emit.

Why this behavior? How do you know when to use socket.emit or socket.send?


Source: (StackOverflow)

node.js, socket.io with SSL

I'm trying to get socket.io running with my SSL certificate however, it will not connect.

I based my code off the chat example:

var https = require('https');
var fs = require('fs');
/**
 * Bootstrap app.
 */
var sys = require('sys')
require.paths.unshift(__dirname + '/../../lib/');

/**
* Module dependencies.
*/

var express = require('express')
  , stylus = require('stylus')
  , nib = require('nib')
  , sio = require('socket.io');

/**
 * App.
 */
var privateKey = fs.readFileSync('../key').toString();
var certificate = fs.readFileSync('../crt').toString();
var ca = fs.readFileSync('../intermediate.crt').toString();

var app = express.createServer({key:privateKey,cert:certificate,ca:ca });


/**
 * App configuration.
 */

...

/**
 * App routes.
 */

app.get('/', function (req, res) {
  res.render('index', { layout: false });
});

/**
 * App listen.
 */

app.listen(443, function () {
  var addr = app.address();
  console.log('   app listening on http://' + addr.address + ':' + addr.port);
});

/**
 * Socket.IO server (single process only)
 */

var io = sio.listen(app,{key:privateKey,cert:certificate,ca:ca});
...

If I remove the SSL code it runs fine, however with it I get a request to http://domain.com/socket.io/1/?t=1309967919512

note its not trying https, which causes it to fail.

I'm testing on chrome, since it is the target browser for this application.

I appologize if this is a simple question, I'm a node/socket.io newb.

Thanks!


Source: (StackOverflow)

Node.js client for a socket.io server

I have a socket.io server running and a matching webpage with a socket.io.js client. All works fine.

But, I am wondering if it is possible, on another machine, to run a separate node.js application which would act as a client and connect to the mentioned socket.io server?

EDIT SOLUTION:

After installing socket.io-client:

npm install socket.io-client

This is how the client code looks like:

var io = require('socket.io-client'),
socket = io.connect('localhost', {
    port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

Thanks alessioalex.


Source: (StackOverflow)

socket.io rooms or namespacing?

I am investigating nodejs/socket.io for real time chat, and I need some advice for implementing rooms.

Which is better, using namespace or using the room feature to completely isolate grops of chatters from each other?

what is the real technical difference between rooms and namespace?

Is there any resource usage difference?


Source: (StackOverflow)

The app references non-public selectors in Payload/.app/: decoder

I am getting this warning while submitting app to the Apps store through organizer.

The app references non-public selectors in Payload/.app/: decoder

i know we get this warning if we use any Third Party API in our application. I have used SOCKETIO-ObjC library for chat functionality in application. Also used facebook iOS sdk for fb implementation.So i am not getting exactly what causes this warning.! Please find attached ScreenShot for better understanding


Source: (StackOverflow)

Socket.IO issue with control chars

I am implementing an application that uses websockets and a console accessed via Telnet. There is a communication between the connection established via websockets and the console. I am experiencing a weird issue:

  • If I send a string constant to an established socket when something is entered in the console it works ok.
  • If I send a string received from the console scope It seems to open a new socket (not sure) because in the debug log I see it and in the browser side (websockets) it alerts me of a new connection.
  • If I send a local string (instead of the one received from the other scope) it's sent correctly. (commented line: client.send(message) )

I share here the nodeJS code, take into account that this is now a test app so it's assumed only one socket and websockets connection:

// Sample based on: http://elegantcode.com/2011/05/04/taking-baby-steps-with-node-js-websockets/
// Changed for sockets.io 6.x => 7.x


var events = require('events');
var eventEmitter = new events.EventEmitter();

var http = require('http');
var socketIO = require('socket.io');
var static = require('node-static');

var port = 2000;

var clientFiles = new static.Server('./client');

var httpServer = http.createServer(
    function(request, response) {
        request.addListener('end', function() { 
            clientFiles.serve(request, response);
       });
    })

httpServer.listen(port);
console.log("Server running at port: " + port);

var io = require('socket.io').listen(httpServer);

var webSocket = io.sockets;

webSocket.on('connection', function(client) {
    client.send('Please enter a user name ...');
    var userName;

    eventEmitter.on('someOccurence', function(message) {
        console.log("Received: " + message);
        client.send('Line Received');
        var s = 'popo';
        client.send(s);
        //client.send(message);
    });


    client.on('message', function(message) {
        console.log(message);

        if(!userName) {
            userName = message;
            client.broadcast.send(message + ' has entered the zone.');
            return;
        }

        var broadcastMessage = userName + ': ' + message;
        client.broadcast.send(broadcastMessage);
        client.send("Repeated here: " + message);
    });

    client.on('disconnect', function() {
        var broadcastMessage = userName + ' has left the zone.';
        client.broadcast.send(broadcastMessage);
    });
});


var lines = require('lines-adapter');
var net = require('net');

var server = net.createServer(function (socket) {
    socket.write("Welcome to the Server\r\n");

    lines(socket, 'utf8')
    .on("data",
        function(line) {
            console.log("Line received: " + line);
            eventEmitter.emit('someOccurence', line);
        }
    )
    .end("end",
        function() {
            console.log("End of Stream");
        }
    );
});

server.listen(1337, "127.0.0.1");

UPDATE: I just tested with socket.io 0.8.6 and nodeJS 0.4.12 without this issue. I will keep this question here for future reference.


Source: (StackOverflow)

Pusher vs Pubnub vs open source Socket.io / SignalR.net / Faye / jWebSocket [closed]

I'm evaluating Pusher and PubNub at the moment to enable bi-directional realtime communications between my primarily web clients and my servers. Both look impressive, with Pusher's docs seeming to be better, and PubNub's scalability and reliability clearly a strong point for them.

However, as I am managing a budget, I am concerned that Pusher & PubNub costs may become an issue for us, and am therefore considering using one of the open source alternatives out there - I've looked primarily at Socket.io, Faye and jWebSocket.

I have my concerns though running the service myself though:

  • Has anyone actually scaled a Socket.io or other open source solution to multiple servers before? PubNub claim to deal with 1M messages a second!, I somewhat doubt Socket.io could do that without an unfathomable number of servers, if it would work at all.
  • Are there features in the paid services that I am likely going to miss down the line should I go with the open source solutions?
  • Is latency really going to be a concern if I have my server on AWS anyway? PubNub are in multiple locations so I expect this should reduce latency although if a message needs to be sent from the US to Japan, having a server in Japan wouldn't help with latency as it still needs to travel there one way or another.

Thanks for the advice.


Source: (StackOverflow)

Update all clients using Socket.io?

Is it possible to force all clients to update using socket.io? I've tried the following, but it doesn't seem to update other clients when a new client connects:

Serverside JavaScript:

I'm attempting to send a message to all clients, which contains the current number of connected users, it correctly sends the amount of users.... however the client itself doesn't seem to update until the page has been refreshed. I want this to happen is realtime.

var clients = 0;
io.sockets.on('connection', function (socket) {
  ++clients;
  socket.emit('users_count', clients);    
  socket.on('disconnect', function () {
    --clients;
  });
});

Clientside JavaScript:

var socket = io.connect('http://localhost');

socket.on('connect', function(){
  socket.on('users_count', function(data){
    $('#client_count').text(data);
    console.log("Connection");
  });
});

Source: (StackOverflow)