通过 UDP 发送数据

UDP 是一种无连接协议。发送到其他进程或计算机的消息不会建立任何类型的连接。如果你的消息已收到,则无法自动确认。UDP 通常用于延迟敏感的应用程序或发送网络广播的应用程序中。

以下代码使用 UDP 将消息发送到侦听 localhost 端口 6667 的进程

请注意,发送后无需关闭套接字,因为 UDP 是无连接的

from socket import socket, AF_INET, SOCK_DGRAM
s = socket(AF_INET, SOCK_DGRAM)
msg = ("Hello you there!").encode('utf-8')  # socket.sendto() takes bytes as input, hence we must encode the string first.
s.sendto(msg, ('localhost', 6667))