python socket 发生UDP 和 UDPServer接受UDP实例

python UDP 通信

socket 发送udp 示例

复制代码
import socket
import time

# 初始化端口
self.ip_port = (host_msg,ip_port_msg)
# 创建 socket
self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  
# 发送
self.client.sendto(self.msg,self.ip_port)
# 关闭 soceket
self.client.close()

UDPServer 用于接收 UDP 示例

复制代码
# 继承  UDPServer 
class MyUDPServer(UDPServer):

    def __init__(self, server_address, RequestHandlerClass, queue):
        # 传递用于接受的队列
        self.udp_queue = queue  
        # UDPServer 实例化           地址          服务函数
        UDPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=True)


class Handler(BaseRequestHandler):
    def handle(self):
        self.data = self.request[0].strip()
        self.server.udp_queue.put(self.data)

复制代码
class my_udp_server():
    def __init__(self,udp_queue):
        super().__init__()
        # 创建用于接受的队列
        self.queue = udp_queue
        
    # 创建服务,
    def open_udp_server(self,ip,port):  
            ADDR = ip, port
            #实例化 MyUDPServer 类
            self.UDPServer = MyUDPServer(ADDR, Handler, self.queue)  
            #创建线程,将UDPServer的serve_forever  传递进线程成中
            self.server_thread = threading.Thread(target=self.UDPServer.serve_forever)  
            #设置后台线程
            self.server_thread.setDaemon(True) 
            #启动线程
            self.server_thread.start()   

    def close_udp_server(self):  
            #服务  shutdown
            self.UDPServer.shutdown()
            #关闭服务
            self.UDPServer.server_close()


# 创建 队列用于接收
self.udp_queue= Queue(maxsize=5)
# 实例化 udp 服务
self.udp_server = my_udp_server(self.udp_queue)
# 打开服务
self.udp_server.open_udp_server("192.168.1.100",6000)
# 关闭服务
self.udp_server.close_udp_server()
相关推荐
databook9 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室10 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三11 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271115 小时前
Python之语言特点
python
刘立军15 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机18 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机20 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i21 小时前
django中的FBV 和 CBV
python·django
c8i21 小时前
python中的闭包和装饰器
python
这里有鱼汤1 天前
小白必看:QMT里的miniQMT入门教程
后端·python