Twisted中来自客户端的两个tcp连接

时间:2015-09-07 11:04:06

标签: python twisted

我是新来的扭曲。我写了一个连接到两个端口8037和8038上的服务器的客户端。我知道工厂创建了两个连接对象。现在,当我按下Ctrl-C时,它会显示

Connection Lost Connection to the other side was lost in a non clean fashion.
Connection Lost Connection to the other side was lost in a non clean fashion. 

以下是代码:

from twisted.internet import protocol,reactor

class TestClient(protocol.Protocol):
  def __init__(self):
    pass

  def connectionMade(self):
    print "Connected "
    self.sayHello()

  def connectionLost(self,reason):
    self.transport.loseConnection()

  def sayHello(self):
    self.transport.write("Hello")

  def dataReceived(self,data):
    print "Received data ",data



class TestClientFactory(protocol.ClientFactory):
  def buildProtocol(self,addr):
    return TestClient()

  def clientConnectionFailed(self,connectory,reason):
    print "Connection Failed ",reason.getErrorMessage()

  def clientConnectionLost(self,connector,reason):
    print "Connection Lost ",reason.getErrorMessage()

reactor.connectTCP("<server_ip>",8037,TestClientFactory())
reactor.connectTCP("<server_ip>",8038,TestClientFactory())
reactor.run()
  1. 如何让客户端干净地关闭两个tcp连接?
  2. 如何只为一个连接调用sayHello()方法?
  3. 我是新来的扭曲,所以一个例子会有所帮助。

    由于

2 个答案:

答案 0 :(得分:1)

当你连接时,如果你想调用sayHello,你可以使用rpc的想法。

例如,您发送一条消息,例如'sayHello_args',解析消息并通过args调用sayhello。

如果您不想发送任何消息。连接时,请调用d.addCallback(sayHello)。      d = defer.succeed(0) d.addCallback(lambda _ : self.sayHello())

如果要关闭连接,请使用reactor.stop()

enter image description here

enter image description here

答案 1 :(得分:0)

不干净的连接关闭真的没什么好担心的。获得干净的退出可能会使您的关机过程变得更慢和更缓慢,因为它需要一堆额外的代码,并且您必须能够处理异常的网络连接终止,无论如何。实际上称之为&#34;清洁&#34;可能甚至有点误导:&#34;同时确认&#34;可能更接近于它实际告诉你关于如何关闭连接的内容。

至于如何致电sayHello,我并不完全理解您的问题,但如果您使用AMP,则在连接的另一侧调用方法非常简单。