I'm experimenting with building a websocket's based application.
I am wondering whether it's possible to send a message to all active connections as they are persistant.
Say I'm running a live auction site and I have multiple users watching the auction page, each of them is connected via sockets to my server. Now let's say one user raises the bid. I want to send a message to all connected clients. Easiest way is to have the clients poll the server via socket every second, but I think the idea of websockets is to have true bi-directional communication.
How can this be done?
thanks in advance,
Rotem
The theoretical limit is 65k connections per IP address but the actual limit is often more like 20k, so we use multiple addresses to connect 20k to each (50 * 20k = 1 mil). I then run the web server as root by typing sudo -i followed by ulimit -n 1024000 and then node examples/WebSocket. js (in the uWebSockets.
Node. js can maintain many hundreds of WebSockets connections simultaneously. WebSockets on the server can become complicated as the connection upgrade from HTTP to WebSockets requires handling. This is why developers commonly use a library to manage this for them.
Chrome has a limit of 6 connections per host name, and a max of 10 connections. This essentially means that it can handle 6 requests at a time coming from the same host, and will handle 4 more coming from another host at the same time.
socket.io solution:
// note, io.listen() will create a http server for you
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
io.sockets.emit('this', { will: 'be received by everyone' });
socket.on('private message', function (msg) {
console.log('I received a private message from ', socket.id, ' saying ', msg);
// Echo private message only to the client who sent it
socket.emit('private message', msg);
});
socket.on('disconnect', function () {
// This will be received by all connected clients
io.sockets.emit('user disconnected');
});
});
all_active_connections = {};
webocket server (there are many), do same manually:
var ws = require("ws");
global_counter = 0;
all_active_connections = {};
ws.createServer(function (websocket)
{
websocket.on('connect', function()
{
var id = global_counter++;
all_active_connections[id] = websocket;
websocket.id = id;
}).on('data', function (data) {
if (data == 'broadcast me!')
{
for (conn in all_active_connections)
all_active_connections[conn].write(data);
}
}
}).on('close', function() {
delete all_active_connections[websocket.id];
});
}).listen(8080);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With