twisted怎么做异步的tcp协议通讯

我用twisted主要时项目上需要一边进行发送命令给机器人,一边又需要不断去解析出来机器人实时上报的状态报文和服务端应答报文。就下面图示一样,使用twisted可以让下发命令和解析状态异步运行,互不影响。
客户端 机器人 desition命令 desition命令已经收到 主动上报状态right 主动上报状态right 主动上报状态right 主动上报状态right 断开连接 断开连接已经收到 客户端 机器人

怎么使用twisted

首先就是建立tcp连接,然后再实现协议报文的处理细节。协议的细节里用来构建命令发送和状态报文的解析。注意协议可以为tcp、http\https都可以。我这里例子用的是tcp

python 复制代码
#这里是构建tcp的连接使用,建立好连接,接下来才可以处理协议报文了。
from twisted.internet.protocol import ClientFactory
class ClientFactory(ClientFactory):
    """Tcp 连接模块,这里继承了twisted里的ClientFactory"""

    def startedConnecting(self, connector):
        print_with_timestamp('正在尝试连接...')

    def buildProtocol(self, addr):
        print_with_timestamp('已连接。')
        return ClientProtocol()

    def clientConnectionLost(self, connector, reason):
        print_with_timestamp('连接丢失。原因:', reason)

    def clientConnectionFailed(self, connector, reason):
        print_with_timestamp('连接失败。原因:', reason)

tcp连接构建完成后,我们处理协议报文的问题。

python 复制代码
from twisted.protocols.basic import LineReceiver
class ClientProtocol(LineReceiver):
	#这里继承了LineReceiver
	delimiter = b'\x5F\x5F\x65\x6E\x64\x5F\x5F'
	'''这个步骤对于tcp报文非常重要,tcp有帧尾代表一帧报文的结束符号。一个60字节的报文,真正传输时,tcp协议会一次性传输1024个字节以节省传输耗时,所以需要我们主动进行断开报文。delimiter就是这样用的。'''
	def __init__(self):
		reactor.callInThread(self.user_input)
		#开启的一个线程,专门用来发送命令,使得发送和接受互不影响。
	def lineReceived(self, line):
		print(line)
		这里时根据delimiter断包(防止粘包)后,一帧帧的tcp报文。
	def send(self,frame):
		'''这里用了发送tcp报文,frame需要你根据自己的情况构建报文结构,发送为16进制字节流,一般包含帧头、帧尾、帧长度、命令字节、数据字节组成一帧'''
		if self.transport:
			self.transport.write(frame)
			
	def user_input(self):
		'''这里接受实时用户输入的命令,并发送给机器'''
		    command_key = input("请输入要发送的命令关键字(输入'exit'退出): ").strip().upper()
            if command_key == 'EXIT':
                print_with_timestamp("正在退出...")
                self.transport.loseConnection()
                break

再写一个main函数启动运行即可

python 复制代码
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
def main():
    client_input = ClientFactory()
    sender_endpoint = TCP4ClientEndpoint(reactor, HOST, PORT)
    sender_endpoint.connect(client_input)
    reactor.run()
相关推荐
开***能2 小时前
高炉项目中DeviceNET到Ethernet的转换奥秘
网络·网络协议·自动化
努力也学不会java2 小时前
【网络原理】 网络编程套接字
java·开发语言·网络·网络协议·tcp/ip·php
不老刘2 小时前
Uni-app网络请求AES加密解密实现
网络·uni-app
芷栀夏3 小时前
CasaOS上部署1Panel开源运维面板远程在线访问配置实操指南
linux·服务器·网络
xinxiyinhe4 小时前
Web安全:威胁解析与综合防护体系构建
网络
✿ ༺ ོIT技术༻4 小时前
Linux:TCP保证可靠性的方案(2)
网络·网络协议·tcp/ip
SunsPlanter5 小时前
RPC 是什么?为什么有了 HTTP 还要用 RPC
网络协议·http·rpc
shanks666 小时前
【Bug】 [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
网络协议·bug·ssl
qq_4298565710 小时前
计算机网络的五层结构(物理层、数据链路层、网络层、传输层、应用层)到底是什么?
网络·计算机网络
奋斗者1号15 小时前
《Crawl4AI 爬虫工具部署配置全攻略》
网络·爬虫