【问题标题】:Push messages to clients in Python在 Python 中向客户端推送消息
【发布时间】:2011-07-27 16:59:10
【问题描述】:

如何实现一个可以在必要时向客户端“推送”消息的系统? 基本上,我需要的是能够将文本从 Python 服务器“推送”到 Python 客户端。然后将文本解析为将在客户端处理的操作(一旦收到“操作文本”,我已经知道如何做这件事)。 我可以每隔几秒钟检查一次正在等待的新“动作文本”——只是我认为它不可靠且无法扩展到成千上万的客户。实时性在这里非常重要。

有什么建议吗?

【问题讨论】:

  • 我倾向于 Twisted 从事那种工作。

标签: python real-time


【解决方案1】:

你可以使用redis发布订阅模型more here

Redis 具有高度可扩展性和快速性。

示例:(来自https://github.com/andymccurdy/redis-py/blob/master/tests/pubsub.py

import redis
import unittest

class PubSubTestCase(unittest.TestCase):
    def setUp(self):
        self.connection_pool = redis.ConnectionPool()
        self.client = redis.Redis(connection_pool=self.connection_pool)
        self.pubsub = self.client.pubsub()

    def tearDown(self):
        self.connection_pool.disconnect()

    def test_channel_subscribe(self):
        self.assertEquals(
            self.pubsub.subscribe('foo'),
            ['subscribe', 'foo', 1]
            )
        self.assertEquals(self.client.publish('foo', 'hello foo'), 1)
        self.assertEquals(
            self.pubsub.listen().next(),
            {
                'type': 'message',
                'pattern': None,
                'channel': 'foo',
                'data': 'hello foo'
            }
            )
        self.assertEquals(
            self.pubsub.unsubscribe('foo'),
            ['unsubscribe', 'foo', 0]
            )

    def test_pattern_subscribe(self):
        self.assertEquals(
            self.pubsub.psubscribe('fo*'),
            ['psubscribe', 'fo*', 1]
            )
        self.assertEquals(self.client.publish('foo', 'hello foo'), 1)
        self.assertEquals(
            self.pubsub.listen().next(),
            {
                'type': 'pmessage',
                'pattern': 'fo*',
                'channel': 'foo',
                'data': 'hello foo'
            }
            )
        self.assertEquals(
            self.pubsub.punsubscribe('fo*'),
            ['punsubscribe', 'fo*', 0]
            )

【讨论】:

  • +1 建议使用 Redis 而不是实现自己的套接字流
【解决方案2】:

我建议让每个客户端都建立到服务器的套接字连接。每个客户端都可以运行一个线程,该线程尝试从套接字进行阻塞读取(将其置于后台线程中),该线程在可用时从套接字中提取信息。然后,每当服务器写入该套接字时,客户端应该立即得到它。客户端的连接应该继承telnetlib.telnet imho,因为它提供了一个方便的read_until 方法。可能是这样的:

class RPCConnection(object, Telnet):
  def __init__(self, host = 'localhost', port = 9198, auto = True):
    Telnet.__init__(self)

    self.host, self.port, self.connected = host, port, False

    if auto:
      self._connect()

  def _connect(self):
    self.open(self.host, self.port)

    self.connected = True

  def _disconnect(self):
    self.close()

    self.connected = False

  def _send(self, dict):
    self.write(json.dumps(dict))

  def _recv(self):
    resp = self.read_until('\n')

    try:
      return json.loads(resp)
    except Exception, e:
      print e
      print resp

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-12
    • 2019-11-12
    • 1970-01-01
    • 2015-03-03
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    相关资源
    最近更新 更多