码迷,mamicode.com
首页 > 编程语言 > 详细

python手记-twisted(4)

时间:2016-07-10 18:40:13      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

from twisted.internet.protocol import Protocol
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.internet.endpoints import TCP4ServerEndpoint
#http://blog.csdn.net/myhaspl
class Echo(Protocol):
       
     def connectionMade(self):
         self.factory.numProtocols=self.factory.numProtocols+1
         self.transport.write("welcome!\nthere are currently %d open connections.\n"%(self.factory.numProtocols,))

     def dataReceived(self,data):
         mydata=data.strip()
	 if mydata!="quit" and  mydata!="quit\r\n" and mydata!="quit\r": 
              self.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/myhaspl
class 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)
endpoint.listen(EchoFactory("myhaspl:"))
reactor.run()

未经博主允许不得转载。http://blog.csdn.net/myhaspl

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

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


$ telnet 120.55.*.* 8001

Trying 120.55.*.* ...

Connected to 120.55.*.* .

Escape character is ‘^]‘.

welcome!

there are currently 1 open connections.

hello

myhaspl:hello

world

myhaspl:world

quit

myhaspl:byebye

Connection closed by foreign host.



python手记-twisted(4)

标签:

原文地址:http://blog.csdn.net/myhaspl/article/details/51867623

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!