我是新来的扭曲。我写了一个连接到两个端口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()
我是新来的扭曲,所以一个例子会有所帮助。
由于
答案 0 :(得分:1)
当你连接时,如果你想调用sayHello,你可以使用rpc的想法。
例如,您发送一条消息,例如'sayHello_args',解析消息并通过args调用sayhello。
如果您不想发送任何消息。连接时,请调用d.addCallback(sayHello)。
d = defer.succeed(0)
d.addCallback(lambda _ : self.sayHello())
如果要关闭连接,请使用reactor.stop()
答案 1 :(得分:0)
不干净的连接关闭真的没什么好担心的。获得干净的退出可能会使您的关机过程变得更慢和更缓慢,因为它需要一堆额外的代码,并且您必须能够处理异常的网络连接终止,无论如何。实际上称之为&#34;清洁&#34;可能甚至有点误导:&#34;同时确认&#34;可能更接近于它实际告诉你关于如何关闭连接的内容。
至于如何致电sayHello
,我并不完全理解您的问题,但如果您使用AMP,则在连接的另一侧调用方法非常简单。