自動鏈接服務器


# -*- coding:cp936 -*-
#!/usr/bin/env python
"""
客戶端的幾個事件響應
startConnecting 正在鏈接服務器
buildProtocol 已鏈接上服務器,建立Protocol
clientConnectionLost 與主機失去鏈接
clientConnectionFailed 與主機鏈接失敗
添加自動鏈接功能,當鏈接主機失敗後;再次進行鏈接
當與主機鏈接失敗後,再次進行鏈接;
"""

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

class EchoClient(Protocol):
    #創建鏈接時發送到服務器端
    def connectionMade(self):
        for i in range(1,100):
            print 'send---',i
            self.transport.write("%s\n"%i)
    #接收到數據並關閉鏈接
    def dataReceived(self, data):
        print "Received---", data
    # #關閉鏈接時調用
    # def connectionLost(self,reason):
    #     print "connection lost",reason

class EchoClientFactory(ClientFactory):
    def startedConnecting(self,connector):
        print("Start to connect")
    def buildProtocol(self,addr):
        print("build protocol")
        return EchoClient()
    def clientConnectionLost(self,connector,reason):
        print("client connection lost" + str(reason))
        # 與主機斷開鏈接後,將自動進行鏈接
        ReconnectingClientFactory.clientConnectionLost(self,connector,reason)
    def clientConnectionFailed(self,connector,reason):
        print("client connection failed:" + str(reason))
        # 當鏈接失敗後,自動進行鏈接
        ReconnectingClientFactory.clientConnectionFailed(self,connector,reason)

reactor.connectTCP("localhost",8001,EchoClientFactory())
reactor.run()



#服務器端
from twisted.internet.protocol import Protocol,Factory
from twisted.internet import reactor

class Echo(Protocol):
    def dataReceived(self, data):
        # As soon as any data is received, write it back
        print self.transport.client
        print data
        self.transport.write(data)
        print '----------'
class EchoFactory(Factory):
    def buildProtocol(self, addr):
        return Echo()

reactor.listenTCP(8001, EchoFactory())
reactor.run()
相關文章
相關標籤/搜索