python手记-twisted(2)

关闭连接

Xshell 5 (Build 0655)
Copyright (c) 2002-2015 NetSarang Computer, Inc. All rights reserved.


Type `help' to learn how to use Xshell prompt.
[c:\~]$ telnet 120.55.*.* 8001

Connecting to 120.55.*.*:8001...
Connection established.
To escape to local shell, press 'Ctrl+Alt+]'.
hello
hello
world
world
quit
Connection closed by foreign host.


Disconnected from remote host(120.55.69.31:8001) at 17:45:33.


Type `help' to learn how to use Xshell prompt.

本博客所有内容是原创,如果转载请注明来源

http://blog.csdn.net/myhaspl/


如果输入quit则关闭连接,通过下面语句

self.transport.loseConnection()

protocol不保存永久数据,每个连接初始化生成protocol实例,连接关闭时退出。而永久数据由factory负责

^C[myhaspl@iZ23mdqdp94Z ~]$ cat  learn/l1/myserver.pl
from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint

class Echo(Protocol):
    
     def dataReceived(self,data):
         if data!="quit":
              self.transport.write(data)
         else:
              self.transport.loseConnection()

class EchoFactory(Factory):
     def buildProtocol(self,addr):
          return Echo()    

endpoint=TCP4ServerEndpoint(reactor,8001)
endpoint.listen(EchoFactory())
reactor.run()


你可能感兴趣的:(python手记-twisted(2))