我通过两个不同的端口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,该如何识别连接?
最佳答案
您可以维护一个全局字典/列表来保存连接,并在connectionMade()/connectionLost()
中添加/删除连接。
或者您可以使用ClientCreator方便
关于python - 如何识别扭曲的客户?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25758273/