刘亚壮的专栏

持之以恒,贵在坚持,每天进步一点点。。。

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

转载请注明出处: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()

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l1028386804/article/details/79965350
文章标签: Python
个人分类: python
所属专栏: Python
上一篇Python之——Undefined variable from import: listenTCP
下一篇Python之——Python之生成并解析电子邮件
想对作者说点什么? 我来说一句

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

关闭
关闭