是否可以向所有活动的 WebSocket 连接发送消息?使用 node.js 或 python tornado websockets [英] Is it possible to send a message to all active WebSocket connections? Using either node.js or python tornado websockets
问题描述
我正在尝试构建基于 websocket 的应用程序.
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.
假设我正在运行一个实时拍卖网站,并且有多个用户在观看拍卖页面,每个用户都通过套接字连接到我的服务器.现在假设一位用户提高了出价.我想向所有连接的客户端发送消息.最简单的方法是让客户端每秒通过套接字轮询服务器,但我认为 websockets 的想法是实现真正的双向通信.
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.
如何做到这一点?
提前致谢,
罗特姆
推荐答案
socket.io解决方案:
// 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 服务器(有很多),手动执行相同操作:
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);
这篇关于是否可以向所有活动的 WebSocket 连接发送消息?使用 node.js 或 python tornado websockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!