服务端
# -*- coding: utf-8 -*-
# @Time : 2018/9/19 21:41
# @Author : cxa
# @File : tsTservTW.py
# @Software: PyCharm
'''
Twisted Reactor时间戳TCP服务器
'''
from twisted.internet import protocol, reactor
from time import ctime
import msgpack
PORT = 21567
class TSServProtocol(protocol.Protocol):
def connectionMade(self):
'''
当客户端连接的时候会执行该方法
:return:
'''
clnt = self.clnt = self.transport.getPeer().host
print(f"...来自的{clnt}链接:")
def dataReceived(self, data):
'''
接收到客户端的数据
:param data:
:return:
'''
print(f"来自客户端:{msgpack.unpackb(data,encoding='utf')}")
data = f"{ctime()}:来自服务器:你好"
self.transport.write(msgpack.packb(data))
if __name__ == '__main__':
# 创建一个协议工厂,之所以称之为工厂是因为,每次得到一个
# 接入连接时,都能"制造"协议的一个实例。
factory = protocol.Factory()
factory.protocol = TSServProtocol
print("....等待链接..")
# 使用reactor安装一个TCP监听器,检查服务请求。
# 当它接收到一个请求时,就会创建一个TSServProtocol实例来处理那个客户端的事务。
reactor.listenTCP(PORT, factory)
reactor.run()
客户端
# -*- coding: utf-8 -*-
# @Time : 2018/9/19 21:57
# @Author : cxa
# @File : tsTclntTW.py
# @Software: PyCharm
'''
创建Twisted Reactor TCP客户端
'''
from twisted.internet import protocol, reactor
import msgpack
HOST = 'localhost'
PORT = 21567
class TSClntProtocol(protocol.Protocol):
def sendData(self):
data = input('>')
if data:
print(f'...发送数据 {data}')
self.transport.write(msgpack.packb(data))
else:
self.transport.loseConnection()
def connectionMade(self):
self.sendData()
def dataReceived(self, data):
print(msgpack.unpackb(data, encoding="utf8"))
self.sendData()
class TSClntFactory(protocol.ClientFactory):
protocol = TSClntProtocol
clientConnctionLost = clientConnctionFailed = lambda self, connector, reason: reactor.stop()
if __name__ == '__main__':
reactor.connectTCP(HOST, PORT, TSClntFactory())
reactor.run()