【问题标题】:Twisted with multiple ports, protocols, and reactors扭曲了多个端口、协议和反应器
【发布时间】:2014-10-29 01:31:45
【问题描述】:

twisted 是否支持同时使用不同的“处理程序”(每个端口的不同回调集)监听多个端口?本质上,我希望我的进程在一个进程中托管两台服务器,每台服务器执行不同的功能。我需要使用两个反应器吗?

【问题讨论】:

  • 一个反应器。每个过程始终只有一个反应器。但它可以监听多个端口,服务多个协议,在提供 HTTP 内容的同一端口上运行 WebSocket 服务器等等。 reactor 是所有传入事件 en.wikipedia.org/wiki/Reactor_pattern 的调度程序

标签: python network-programming


【解决方案1】:

是的,例如,修改 quote server example 您可以添加第二个实例,以不同的引用在不同的端口上侦听:

from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
        # self.factory was set by the factory's default buildProtocol:
        self.transport.write(self.factory.quote + '\r\n')
        self.transport.loseConnection()


class QOTDFactory(Factory):

    # This will be used by the default buildProtocol to create new protocols:
    protocol = QOTD

    def __init__(self, quote=None):
        self.quote = quote or 'An apple a day keeps the doctor away'

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))

endpoint2 = TCP4ServerEndpoint(reactor, 8008)
endpoint2.listen(QOTDFactory("another configurable quote"))

reactor.run()

输出:

$ nc localhost 8007
configurable quote
$ nc localhost 8008
another configurable quote

【讨论】:

  • 很棒的答案。如果我想加入其他东西,例如扭曲的 WebSocket,该怎么办。我可以和那些一起做吗?
  • @horsehair 我没有尝试过,但它应该可以正常工作。反应器基本上轮询每个套接字并在数据到达时将数据发送到相应的协议。你在使用autobahn.ws 吗?
  • 我正在尝试确定是否应该使用 autobahn.ws,但我开始认为 Twister 具有内置功能,使得使用 autobahn 变得多余。至少对于只传递消息的简单 WebSocket。没有?
  • @horsehair 我不是最新的开发,但我上次检查 WebSocket 分支仍在开发中
  • @PeterGibson,如何使用 twistd 在守护程序模式下运行演示?
猜你喜欢
  • 2011-05-17
  • 2012-07-03
  • 1970-01-01
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-10
  • 1970-01-01
相关资源
最近更新 更多