python开发----twisted使用例子

服务端:

 1 #!/usr/bin/env python
 2 
 3 from twisted.internet import protocol, reactor
 4 from time import ctime
 5 
 6 PORT = 21567
 7 
 8 
 9 class TSServProtocol(protocol.Protocol):
10     def connectionMade(self):
11         clnt = self.clnt = self.transport.getPeer().host
12         print '...conneting from:', clnt
13 
14     def dataReceived(self, data):
15         self.transport.write('[%s] %s' % (ctime(), data))
16 
17 factory = protocol.Factory()
18 factory.protocol = TSServProtocol
19 print 'waiting for connecting...'
20 reactor.listenTCP(PORT, factory)
21 reactor.run()

 

客户端:

#!/usr/bin/env python

from twisted.internet import protocol, reactor

HOST = 'localhost'
PORT = 21567

class TSClntProtocol(protocol.Protocol):
    def sendData(self):
        data = raw_input('> ')
        if data:
            print '...sending %s...' % data
            self.transport.write(data)
        else:
            self.transport.loseConnection()

    def connectionMade(self):
        self.sendData()

    def dataReceived(self, data):
        print data
        self.sendData()

class TSClntFactory(protocol.ClientFactory):
    protocol = TSClntProtocol
    clientConnectionLost = clientConnectionFailed = lambda self, connector, reason: reactor.stop()

reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()

 

 

例子来源:《python核心编程》

posted @ 2016-03-21 13:27  游荡的沙  阅读(182)  评论(0)    收藏  举报