`

python网络框架twisted TCP客户端连接服务端例子

阅读更多

服务端:

from twisted.internet import reactor
from twisted.internet.protocol import Factory,Protocol

class Echo(Protocol):
    
    def connectionMade(self):
        self.transport.write('hello yy:')
    #    self.transport.loseConnection()        
        
        
    def dataReceived(self,data):
         print data
         self.transport.write("good")
        

factory=Factory()
factory.protocol=Echo

reactor.listenTCP(1234, factory)
reactor.run()

 

 

 

客户端:

 

from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet import reactor

class Echo(Protocol):
   
    
        
    def dataReceived(self, data):
       
        stre=raw_input("请输入发送到服务器的内容:")
        self.transport.write(stre)                   
            

class EchoClientFactory(ClientFactory):
    def startedConnecting(self, connector):
        print 'Started to connect.'

    def buildProtocol(self, addr):
        print addr
        return Echo()

    def clientConnectionLost(self, connector, reason):
        print 'Lost connection.  Reason:', reason

    def clientConnectionFailed(self, connector, reason):
        print 'Connection failed. Reason:', reason
        
        

reactor.connectTCP('127.0.0.1', 1234, EchoClientFactory())
reactor.run()

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics