2015-09-07 232 views
1

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

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()方法?

我是新来扭曲,所以一个例子会有所帮助。

感谢

回答

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

+0

感谢您的回复xiaohen。但是clientConnectionLost中的if条件仍然给我关闭非干净时尚消息的连接。 – Jim

+0

我通过这种方式添加一张新照片;我清理干净。如果你知道解决这个问题的另一种方法,请告诉我。谢谢。 – xiaohen

0

不洁连接关机实在没有什么可担心的。获得一个干净的退出可能会使你的关机过程变得更慢和更缓慢,因为它需要一堆额外的代码,并且无论如何你必须能够处理异常的网络连接终止。实际上将它称为“干净”可能有点误导:“同时确认”可能更接近它实际告诉你连接如何关闭的事实。

至于如何调用sayHello,我没有完全理解你的问题,但如果你使用AMP,在连接的另一端调用一个方法很简单。

+1

感谢您的回复雕文。我编辑了上面TestClient的代码。我在连接完成后调用self.sayHello()。我只是为了一个连接而调用sayHello()的意思是,在上面的代码中,在端口8037和8038上的服务器建立连接后,两个端口上的客户端都会发送“Hello”消息,对吧? 。有没有办法只在一个端口上发送该消息,即8037或8038?谢谢 – Jim

+0

我不明白你在问什么。如果你希望连接到端口8038的客户端执行与“TestClientFactory”不同的操作,可以实例化除TestClientFactory之外的东西,或者给TestClientFactory一个构造器参数,它传递给TestClient来告诉它做一些事情不同。但这与Twisted无关;如果你想Python对象做不同的事情,你只需要制作不同的Python对象:) – Glyph

+0

另外,你可能不应该直接使用'connectTCP'。使用[终结点](https://twistedmatrix.com/documents/15.4。0/core/howto/endpoints.html)。 – Glyph