通過 UDP 接收資料
UDP 是一種無連線協議。這意味著傳送訊息的對等體不需要在傳送訊息之前建立連線。socket.recvfrom
thus 返回一個元組(msg
[套接字收到的訊息],addr
[傳送者的地址])
僅使用 socket
模組的 UDP 伺服器:
from socket import socket, AF_INET, SOCK_DGRAM
sock = socket(AF_INET, SOCK_DGRAM)
sock.bind(('localhost', 6667))
while True:
msg, addr = sock.recvfrom(8192) # This is the amount of bytes to read at maximum
print("Got message from %s: %s" % (addr, msg))
以下是使用 socketserver.UDPServer
的替代實現:
from socketserver import BaseRequestHandler, UDPServer
class MyHandler(BaseRequestHandler):
def handle(self):
print("Got connection from: %s" % self.client_address)
msg, sock = self.request
print("It said: %s" % msg)
sock.sendto("Got your message!".encode(), self.client_address) # Send reply
serv = UDPServer(('localhost', 6667), MyHandler)
serv.serve_forever()
預設情況下,sockets
塊。這意味著指令碼的執行將一直等到套接字接收資料。