本文實例講述了Python實現(xiàn)基于socket的udp傳輸與接收功能。分享給大家供大家參考,具體如下:
udp的傳輸與接收
windows網(wǎng)絡調試助手下載:https://pan.baidu.com/s/1IwBWeAzGUO1A3sCWl20ssQ
提取碼:68gr
或者點擊此處本站下載。
一.基本用法
1.創(chuàng)建套接字
udp_socket = socket.socket(socket.AF_INET,cosket.SOCK_DGRAM)localaddr = ("",port)udp_socket.bind(localaddr)
2.使用套接字收發(fā)數(shù)據(jù)
udp_socket.sendto("xxxx").encode("utf-8"),("ip",port)udp_socket.recvfrom(1024)
3.關閉套接字
udp_socket.close()
二.發(fā)送數(shù)據(jù)流程
1.創(chuàng)建套接字 2.發(fā)送數(shù)據(jù) 3.關閉import socketdef main(): # 創(chuàng)建一個套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: # 從鍵盤獲取數(shù)據(jù) send_data = input("請輸入要發(fā)送的數(shù)據(jù):") # 退出函數(shù) if send_data == "exit": break # 可以使用套接字收發(fā)數(shù)據(jù),此時未綁定發(fā)送的端口號,系統(tǒng)每次會隨機分配一個 # udp_socket.sendto("hahaha",對方的IP和port) # udp_socket.sendto(b"lalala123",("172.17.3.97",8080)) udp_socket.sendto(send_data.encode("gbk"),("172.17.3.97",8080)) #由于接收是在Windows上,而Windows中默認編碼為gbk # 關閉套接字 udp_socket.close()if __name__ == '__main__': main()
三.接收數(shù)據(jù)流程
1.創(chuàng)建套接字 2.綁定本地信息(ip和port) 3.接收數(shù)據(jù) 4.關閉import socketdef main(): # 1創(chuàng)建套接字 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 2.綁定一個本地信息 localaddr = ("",7788) # 必須綁定自己電腦IP和port udp_socket.bind(localaddr) # 3.接收數(shù)據(jù) while True: recv_data = udp_socket.recvfrom(1024) # recv_data存儲元組(接收到的數(shù)據(jù),(發(fā)送方的ip,port)) recv_msg = recv_data[0] # 信息內(nèi)容 send_addr = recv_data[1] # 信息地址 # 4.打印接收到的數(shù)據(jù) # print(recv_data) print("信息來自:%s 內(nèi)容是:%s" %(str(send_addr),recv_msg.decode("gbk"))) # 5.退出套接字 udp_socket.close()if __name__ == "__main__": main()
運行此程序
在網(wǎng)絡調試助手中發(fā)送消息
發(fā)送三次“你好”
發(fā)送三次“hello”
回到pycharm查看信息
更多關于Python相關內(nèi)容可查看本站專題:《Python Socket編程技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
新聞熱點
疑難解答