本文實(shí)例講述了Python 網(wǎng)絡(luò)編程之UDP發(fā)送接收數(shù)據(jù)功能。分享給大家供大家參考,具體如下:
demo.py(UDP發(fā)送數(shù)據(jù)):
import socket # 導(dǎo)入socket模塊def main(): # 創(chuàng)建一個(gè)udp套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 綁定本機(jī)ip和端口號 (發(fā)送數(shù)據(jù)時(shí),如果不綁定,系統(tǒng)會隨機(jī)分配端口號。接收數(shù)據(jù)時(shí),一般需要手動綁定ip和端口) udp_socket.bind(("", 7890)) # 空字符串""表示本地ip # 從鍵盤獲取數(shù)據(jù) send_data = input("請輸入要發(fā)送的數(shù)據(jù):") # 可以使用套接字接收和發(fā)送數(shù)據(jù) # udp_socket.sendto(b"hahahah", ("192.168.33.53", 7788)) # 字符串前的b表示bytes字節(jié)類型 udp_socket.sendto(send_data.encode("utf-8"), ("192.168.33.53", 7788)) # encode將字符串轉(zhuǎn)成bytes類型 # 關(guān)閉套接字 udp_socket.close()if __name__ == "__main__": main()demo.py(UDP接收數(shù)據(jù)):
import socketdef main(): # 1. 創(chuàng)建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2. 綁定本機(jī)ip和端口 udp_socket.bind(("", 7788)) # 綁定本機(jī)的ip和端口(元組類型) ""表示本機(jī)ip # 3. 用套接字接收數(shù)據(jù) recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字節(jié)數(shù)。會阻塞代碼,直到接收到數(shù)據(jù) # recv_data這個(gè)變量中存儲的是一個(gè)元組 (接收到的數(shù)據(jù),(發(fā)送方的ip, port)) recv_msg = recv_data[0] # 字節(jié)類型 存儲接收到的數(shù)據(jù) send_addr = recv_data[1] # 元組 存儲發(fā)送方的地址和端口信息 # 4. 打印接收到的數(shù)據(jù) # print(recv_data) # 元組 (接收到的數(shù)據(jù),(發(fā)送方的ip, port)) print("%s:%s" % (str(send_addr), recv_msg.decode("gbk"))) # decode將字節(jié)轉(zhuǎn)成字符串 # 5. 關(guān)閉套接字 udp_socket.close()if __name__ == "__main__": main()更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答