Python之——基于twisted实现TCP编程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l1028386804/article/details/79965350

转载请注明出处:https://blog.csdn.net/l1028386804/article/details/79965350

1、服务端

# -*- coding:UTF-8 -*-
'''
Created on 2018年4月16日

@author: liuyazhuang
'''
from twisted.internet import protocol, reactor
from time import ctime

PORT = 21567

class TSServProtocol(protocol.Protocol):
    def connectionMade(self):
        clnt = self.clnt = self.transport.getPeer().host
        print '...connected from:', clnt
    
    def dataReceived(self, data):
        self.transport.write("[%s] %s" %(ctime(), data))
    
factory = protocol.Factory()
factory.protocol = TSServProtocol
print 'waiting for connection...'
reactor.listenTCP(PORT, factory)
reactor.run()

2、客户端

# -*- coding:UTF-8 -*-
'''
Created on 2018年4月16日

@author: liuyazhuang
'''
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()

阅读更多

没有更多推荐了,返回首页