2010-07-18 120 views

回答

15

请致电reactor.listenTCPreactor.connectTCP。只要您愿意,您可以拥有许多不同种类的连接 - 服务器或客户端。

例如:

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

class SomeServerProtocol(basic.LineReceiver): 
    def lineReceived(self, line): 
     host, port = line.split() 
     port = int(port) 
     factory = protocol.ClientFactory() 
     factory.protocol = SomeClientProtocol 
     reactor.connectTCP(host, port, factory) 

class SomeClientProtocol(basic.LineReceiver): 
    def connectionMade(self): 
     self.sendLine("Hello!") 
     self.transport.loseConnection() 

def main(): 
    import sys 
    from twisted.python import log 

    log.startLogging(sys.stdout) 
    factory = protocol.ServerFactory() 
    factory.protocol = SomeServerProtocol 
    reactor.listenTCP(12345, factory) 
    reactor.run() 

if __name__ == '__main__': 
    main() 
+0

嗯..我不明白如何使用相同的代码上面监听服务器上连接,你可以见识一下好吗? – Marconi 2010-07-18 20:01:02

+0

另外,你有什么想法,我可能会使用这与标准?假设服务器/客户端可以在后台接受/连接,我也希望能够输入命令。 – Marconi 2010-07-18 20:15:56

+0

上面的代码确实建立了一个传出连接。这就是lineReceived中的connectTCP所做的。这与你想要的有何不同?另外,要将它与stdio一起使用,只需在某处创建一个twisted.internet.stdio.StandardIO实例即可。与listenTCP和connectTCP一样,它也是您可以创建的事件源,并与来自Twisted的任何其他事件源共存。 – 2010-07-20 13:30:06

相关问题