在buildProtocol期间检索侦听端口

时间:2010-11-22 23:51:09

标签: python twisted

我正在修改ServerFactory的buildProtocol方法,基本上工厂侦听端口11000和12000,我有两个协议,一个用于端口每个端口。我正在尝试检索客户端用来监听的端口,以便我可以实例化正确的协议。

离。客户端在端口11000处侦听,协议1被实例化。客户端侦听端口12000,协议2被实例化。

我认为这只能在buildProtocol阶段完成,有没有办法确定用于连接的端口? buildProtocol使用的地址参数是客户端地址,我需要服务器端口。

伪代码:

def buildProtocol(self, address):
  if address connects at port 11000:
    proto = TransformProtocol()
  else:
    proto = TransformProtocol2()
  proto.factory = self
  return proto

1 个答案:

答案 0 :(得分:0)

我认为,您可能需要使用Twisted服务: link text

你的代码变成了:

from twisted.application import internet, service
from twisted.internet import protocol, reactor
from twisted.protocols import basic

class UpperCaseProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        self.transport.write(line.upper() + '\r\n')
        self.transport.loseConnection()

class LowerCaseProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        self.transport.write(line.lower() + '\r\n')
        self.transport.loseConnection()

class LineCaseService(service.Service):

    def getFactory(self, p):
        f = protocol.ServerFactory()
        f.protocol = p
        return f

application = service.Application('LineCase')
f = LineCaseService()

serviceCollection = service.IServiceCollection(application)
internet.TCPServer(11000,f.getFactory(UpperCaseProtocol)).setServiceParent(serviceCollection)
internet.TCPServer(12000,f.getFactory(LowerCaseProtocol)).setServiceParent(serviceCollection)

但是,这里有两个工厂实例。