python收发Udp消息
发Udp消息
udpSend.py
import socket # 设置目标地址和端口 server_address = ('localhost', 6789) # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # 发送数据 message = 'aaaaaaa' print(f"发送:{message}") sent = sock.sendto(message.encode(), server_address) finally: # 关闭套接字 print("关闭套接字") sock.close()
收Udp消息
import socket # 设置服务器地址和端口 server_address = ('localhost', 6789) # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 绑定套接字到地址 sock.bind(server_address) print("服务器启动,等待接收数据...") try: while True: # 等待接收数据(1024字节大小的缓冲区) data, address = sock.recvfrom(1024) print(f"收到数据:{data} 来自 {address}") # 可以在这里添加数据处理逻辑 finally: # 关闭套接字 sock.close()