From Twisted.internet.protocol import protocolfrom twisted.internet import Reactorfrom Twisted.internet.protocol Import factoryfrom twisted.internet.endpoints import Tcp4serverendpoint#http://blog.csdn.net/myhasplclass Echo ( Protocol): def connectionmade (self): self.factory.numprotocols=self.factory.numprotocols+1 self . Transport.write ("Welcome!\nthere is currently%d open connections.\n"% (Self.factory.numProtocols,)) def datareceive D (self,data): Mydata=data.strip () if mydata!= "quit" and mydata!= "quit\r\n" and Mydata!= "quit\r": SE Lf.transport.write (Self.factory.message+data) else:self.transport.write (self.factory.message+ "Byebye \ n ") self.transport.numprotocols=self.factory.numprotocols-1 self.transport.loseConnection () def connectionlost (self, reason): Self.factory.numProtocols = self.factory.numprotocols-1#http://blog.csdn.net/ Myhasplclass echofactory (Factory): #use tHe default Buildprotocol to create protocol Protocol=echo numprotocols=0 def __init__ (self,message=none): Self.message=message or "Hello,world" #http://blog.csdn.net/myhaspl endpoint=tcp4serverendpoint (reactor,8001) ENDP Oint.listen (Echofactory ("MYHASPL:")) Reactor.run ()
Not reproduced without the permission of the blogger. Http://blog.csdn.net/myhaspl
This blog all content is original, if reprint please indicate source http://blog.csdn.net/myhaspl/
$ telnet 120.55.*.* 8001
Trying 120.55.*.* ...
Connected to 120.55.*.* .
Escape character is ' ^] '.
welcome!
There is currently 1 open connections.
Hello
Myhaspl:hello
World
Myhaspl:world
Quit
Myhaspl:byebye
Connection closed by foreign host.
Python-twisted (4)