通過 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))