在buildProtocol期间获取监听端口
我正在修改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
我觉得你可能需要使用Twisted服务:
你的代码可能会变成这样:
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)
不过,这里我们有两个工厂实例。