当前位置: 首页> 健康> 科研 > python udp双向通信

python udp双向通信

时间:2025/8/23 8:13:50来源:https://blog.csdn.net/qq_14874791/article/details/139409333 浏览次数:0次
import json
import socket
import threading
import loggingthislist = []
thisneednum = {}class ChatUdpMain:def __init__(self):#其他原有逻辑 begin#其他原有逻辑 end#  1.创建socket套接字   收self.udp_socket_receive = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # AF_INET表示使用ipv4,默认不变,SOCK_DGRAM表示使用UDP通信协议#  2.绑定端口port  收local_addr_receive = ("127.0.0.1", 45678)  # 默认本机任何ip ,指定端口号45678,用于接收数据self.udp_socket_receive.bind(local_addr_receive)  # 绑定端口#  1.创建socket套接字   发self.udp_socket_send = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # AF_INET表示使用ipv4,默认不变,SOCK_DGRAM表示使用UDP通信协议#  2.绑定端口port  发local_addr_send = ("127.0.0.1", 45671)  # 默认本机任何ip,初始化使用,实际45671没有用self.udp_socket_send.bind(local_addr_send)  # 绑定端口self.start()self.thislist = thislistself.thisneednum = thisneednumdef close(self):try:self.udp_socket_send.close()self.udp_socket_receive.close()except Exception as e:logging.info(e)def send(self, val: str):try:data = str.encode(str(val))self.udp_socket_send.sendto(data, ("127.0.0.1", 45679))  # 默认本机任何ip ,45679是发数据的端口except Exception as e:logging.info(e)# 开启线程def start(self):# 启动新线程接收数据threading.Thread(target=self._recv, name='recv').start()#接收qt发来的实时数据def _recv(self):while 1:try:self.recevalue = self.udp_socket_receive.recv(5000)print("收到数据  ")print(self.recevalue)try:i = 1for k, v in json.loads(self.recevalue).items():if k in self.thislist:self.thisneednum[i] = vi += 1print("数据解析成功")self.jisuan(self.thisneednum)except ValueError:print("ValueError")except Exception as e:logging.info(e)def jisuan(self, d: dict):for i in self.thisneednum:print(self.thisneednum[i])#这里就是计算#得到结果# JSON 字符串json_string = '{"Type": "PCA","name": "Kyrie", "age": 31}'# 解析 JSON 字符串self.data = json.loads(json_string)self.data = json.dumps(self.data)# 给qt发结果self.send(self.data)#self.close()def needcs():with open("config-PCA.ini", "r") as f:str = f.read()strlist = str.split(',')for item in strlist:thislist.append(item)#主函数
def main():needcs()chatUdp = ChatUdpMain()if __name__ == '__main__':main()

关键字:python udp双向通信

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: