python udp双向通信

复制代码
import json
import socket
import threading
import logging

thislist = []
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 = thislist
      self.thisneednum = thisneednum

   def 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 = 1
               for k, v in json.loads(self.recevalue).items():
                  if k in self.thislist:
                     self.thisneednum[i] = v
                     i += 1
               print("数据解析成功")

               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()
相关推荐
爱学习的小鱼gogo28 分钟前
pyhton 螺旋矩阵(指针-矩阵-中等)含源码(二十六)
python·算法·矩阵·指针·经验·二维数组·逆序
言之。1 小时前
Andrej Karpathy 演讲【PyTorch at Tesla】
人工智能·pytorch·python
赵谨言1 小时前
基于Python楼王争霸劳动竞赛数据处理分析
大数据·开发语言·经验分享·python
智启七月2 小时前
谷歌 Gemini 3.0 正式发布:一键生成 Web OS,编程能力碾压竞品
人工智能·python
2401_841495642 小时前
【强化学习】动态规划算法
人工智能·python·算法·动态规划·强化学习·策略迭代·价值迭代
测试19982 小时前
自动化测试报告生成(Allure)
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
DKunYu3 小时前
PyTorch入门
人工智能·pytorch·python·深度学习
ZhengEnCi3 小时前
Python_哈希表完全指南-从字典到高效查找的 Python 编程利器
python
今天没ID3 小时前
Python 集合类型全解析:从网球赛事案例看透字符串、列表、元组、集合与字典(1)
python
小宁爱Python3 小时前
从零搭建 RAG 智能问答系统 4:从多模态架构到 Milvus 向量存储实践
python·milvus