smallseo.info

socket.io

Realtime application framework (Node.JS server) Socket.IO

Node.js, Socket.io, Redis pub/sub high volume, low latency difficulties

When conjoining socket.io/node.js and redis pub/sub in an attempt to create a real-time web broadcast system driven by server events that can handle multiple transports, there seems to be three approaches:

  1. 'createClient' a redis connection and subscribe to channel(s). On socket.io client connection, join the client into a socket.io room. In the redis.on("message", ...) event, call io.sockets.in(room).emit("event", data) to distribute to all clients in the relevant room. Like How to reuse redis connection in socket.io?

  2. 'createClient' a redis connection. On socket.io client connection, join the client into a socket.io room and subscribe to relevant redis channel(s). Include redis.on("message", ...) inside the client connection closure and on receipt of message call client.emit("event", data) to raise the event on the specific client. Like the answer in Examples in using RedisStore in socket.io

  3. Use the RedisStore baked into socket.io and 'broadcast' from the single "dispatch" channel in Redis following the socketio-spec protocol.

Number 1 allows handling the Redis sub and associated event once for all clients. Number 2 offers a more direct hook into Redis pub/sub. Number 3 is simpler, but offers little control over the messaging events.

However, in my tests, all exhibit unexpectedly low performance with more than 1 connected client. The server events in question are 1,000 messages published to a redis channel as quickly as possible, to be distributed as quickly as possible. Performance is measured by timings at the connected clients (socket.io-client based that log timestamps into a Redis list for analysis).

What I surmise is that in option 1, server receives the message, then sequentially writes it to all connected clients. In option 2, server receives each message multiple times (once per client subscription) and writes it to the relevant client. In either case, the server doesn't get to the second message event until it's communicated to all connected clients. A situation clearly exacerbated with rising concurrency.

This seems at odds with the perceived wisdom of the stacks capabilities. I want to believe, but I'm struggling.

Is this scenario (low latency distribution of high volume of messages) just not an option with these tools (yet?), or am I missing a trick?


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)

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)

Using PHP with Socket.io

Is it possible to use Sockets.io on the client side and communicate with a PHP based application on the server? Does PHP even support such a 'long-lived connection' way of writing code?

All the sample code I find for socket.io seems to be for node.js on the server side, so no hlep there.


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)

force client disconnect from server with socket.io and nodejs

Is there any way to disconnect a client with SocketIO, and literally close the connection? So if someone is connected to my server, and I want to close the connection between them and my server, how would I go about doing that?


Source: (StackOverflow)

Socket.IO documentation

Is there any documentation about Socket.IO? Its website just has a poor wiki and there is no full documentation explaining connect, emit, require and so on


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?

thanks


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)

Send response to all clients except sender (Socket.io)

To send something to all clients, you use:

io.sockets.emit('response', data);

To receive from clients, you use:

socket.on('cursor', function(data) {
  ...
});

How can I combine the two so that when recieving a message on the server from a client, I send that message to all users except the one sending the message.

socket.on('cursor', function(data) {
  io.sockets.emit('response', data);
});

Do I have to hack it around by sending the client-id with the message and then checking on the clientside or is there an easier way?


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 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)

Improve this AngularJS factory to use with socket.io

I want to use socket.io in AngularJS. I found the following factory:

app.factory('socket', function ($rootScope) {
    var socket = io.connect();
    return {
        on: function (eventName, callback) {
            socket.on(eventName, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    callback.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callback) {
            socket.emit(eventName, data, function () {
                var args = arguments;
                $rootScope.$apply(function () {
                    if (callback) {
                        callback.apply(socket, args);
                    }
                });
            })
        }
    };

and it is used in the controller like:

function MyCtrl($scope, socket) {
    socket.on('message', function(data) {
        ...
    });
};

the problem is that each time the controller is visited another listener is added, so when a message is received it is handled multiple times.

what can be a better strategy to integrate socket.io with AngularJS ?

EDIT: I know that I can return nothing in the factory and do the listening there, then use $rootScope.$broadcast and $scope.$on in the controllers, but it doesn't look like a good solution.

EDIT2: added to the factory

init: function() {
            socket.removeAllListeners();
}

and call it at the beginning of each controller that use socket.io.

still doesn't feel like the best solution.


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)

Differences between socket.io and websockets

What are the differences between socket.io and websockets in node.js?
Are they both server push technologies? The only differences I felt was,

  1. socket.io allowed me to send/emit messages by specifying an event name.
  2. In the case of socket.io a message from server will reach on all clients, but for the same in websockets I was forced to keep an array of all connections and loop through it to send messages to all clients.

Also, I wonder why web inspectors(like Chrome/firebug/fiddler) are unable to catch these messages(from socket.io/websocket) from server?

Please clarify this.. Thanks.


Source: (StackOverflow)