如何识别扭曲的客户端?

时间:2014-09-10 05:59:11

标签: python connection client protocols twisted

我通过两个不同的端口50000和20000连接到服务器。我会在一个上面写一些数据,有时在另一个上面写一些数据,我会得到一个响应。我怎么能正确地做到这一点?我是否需要在扭曲的ClientFactory子类中创建一些引用?这是我的代码示例:

import sys
from twisted.internet import reactor
from twisted.python import log
from twisted.internet import defer
from twisted.internet.protocol import Protocol, ClientFactory

log.startLogging(sys.stdout)


class PrimeClient(object):
   """
   """
   def __init__(self):
      """
      """
      self.factory = PrimeClientFactory()

   def connect(self):

      servers = [('192.168.110.14', 50000),('192.168.110.14', 20000)]

      for host, port in servers:            
        reactor.connectTCP(host, port, self.factory)



class PrimeProtocol(Protocol):

    def __init__(self):
        pass

    def connectionMade(self):
        print 'Connection made: {} {}'.format(self, self.factory)

    def dataReceived(self, data):
        print 'RCV: {}'.format(data)

    def connectionLost(self, reason):
        print 'Connection lost: {}'.format(reason)



class PrimeClientFactory(ClientFactory):
    """
    """
    protocol = PrimeProtocol

    def __init__(self):
        pass

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed: {} - {}'.format(connector, reason)

    def startedConnecting(self, connector):
        print 'Started connection: {}'.format(connector)



def main():
    prime = PrimeClient()

    prime.connect()
    reactor.run()

if __name__ == "__main__":
    main()

这将创建两个到服务器的连接。那么我如何识别连接,例如,如果我想发送到端口50000?

2 个答案:

答案 0 :(得分:1)

您可以维护一个全局字典/列表来保存连接,并在connectionMade()/connectionLost()中添加/删除与之的连接。

或者您可以使用ClientCreator来表达便利性

答案 1 :(得分:0)

这是关于Twisted的frequently asked question

最简单的解决方案是在connections上制作PrimeClientFactory列表,在self.factory.connections.append(self)connectionMade self.factory.connections.remove(self) connectionLostPrimeProtocol ClientFactory 1}}。

(另外,connectTCP和{{1}}有点过时的方式,你应该use the much newer "endpoints" API for clients instead。)