簡體   English   中英

是否可以向所有活動的 WebSocket 連接發送消息? 使用 node.js 或 python 龍卷風網絡套接字

[英]Is it possible to send a message to all active WebSocket connections? Using either node.js or python tornado websockets

我正在嘗試構建一個基於 websocket 的應用程序。

我想知道是否可以向所有活動連接發送消息,因為它們是持久的。

假設我正在運行一個現場拍賣網站,並且我有多個用戶正在觀看拍賣頁面,每個用戶都通過 sockets 連接到我的服務器。 現在假設一位用戶提高了出價。 我想向所有連接的客戶端發送消息。 最簡單的方法是讓客戶端每秒通過套接字輪詢服務器,但我認為 websockets 的想法是實現真正的雙向通信。

如何才能做到這一點?

提前致謝,

羅騰

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 = {};

webcket 服務器(有很多),手動執行相同操作:

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

對於基於龍卷風/龍卷風的解決方案,您的 SocketConnection class 需要在 class 級別維護連接列表。 您的 on_connect 處理程序會將連接添加到此列表,而 on_close 將刪除它。 有關示例偽代碼,請參閱 Serge S. Koval 的這篇文章 代碼重現如下:

聲明您的 TornadIO 連接 class:

class MyConnection(SocketConnection):
    participants = set()

    @classmethod
    def broadcast(cls, msg):
        for p in cls.participants:
            p.send(msg)

    @classmethod
    def controller_msg(cls, msg):
        cls.broadcast(msg)

在您的設備輪詢線程中,執行以下操作:

while True: 
    datum = file.readline() 
    if len(datum) > 2: 
        t = json.loads(datum) 
        ...
        def callback():
            MyConnection.controller_msg(t)

        io_loop.add_callback(callback)

此外, gevent-socketio支持消息廣播,但它基於 gevent,而不是 tornado。

更新:

tornadio2 已經維護了一個活動會話列表,所以你需要做的就是:

class MyConnection(SocketConnection):
    def broadcast(self, event, message):
        for session_id, session in self.session.server._sessions._items.iteritems():
            session.conn.emit(event, message)

這是因為每個連接實例都引用了它的 session,它引用了用於創建應用程序的全局路由器(存儲為server ),它在_sessions中的SessionContainer object 中維護會話列表。 現在,每當您想在連接 class 中廣播消息時,只需執行以下操作:

self.broadcast('my_custom_event', 'my_event_args')

這個redis + websockets(在龍卷風上)示例應該對您有所幫助。 基本上,您有一個應該通知的聽眾列表,一旦收到消息,就會遍歷該列表並通知他們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM