Python udp網(wǎng)絡程序實現(xiàn)發(fā)送、接收數(shù)據(jù)功能示例
本文實例講述了Python udp網(wǎng)絡程序實現(xiàn)發(fā)送、接收數(shù)據(jù)功能。分享給大家供大家參考,具體如下:
1. udp網(wǎng)絡程序-發(fā)送數(shù)據(jù)
創(chuàng)建一個基于udp的網(wǎng)絡程序流程很簡單,具體步驟如下:
- 創(chuàng)建客戶端套接字
- 發(fā)送/接收數(shù)據(jù)
- 關閉套接字
代碼如下:
#coding=utf-8 from socket import * # 1. 創(chuàng)建udp套接字 udp_socket = socket(AF_INET, SOCK_DGRAM) # 2. 準備接收方的地址 # '192.168.1.103'表示目的ip地址 # 8080表示目的端口 dest_addr = ('192.168.1.103', 8080) # 注意 是元組,ip是字符串,端口是數(shù)字 # 3. 從鍵盤獲取數(shù)據(jù) send_data = input("請輸入要發(fā)送的數(shù)據(jù):") # 4. 發(fā)送數(shù)據(jù)到指定的電腦上的指定程序中 udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. 關閉套接字 udp_socket.close()
運行現(xiàn)象:
在Ubuntu中運行腳本:
在windows中運行“網(wǎng)絡調試助手”:
2. udp網(wǎng)絡程序-發(fā)送、接收數(shù)據(jù)
#coding=utf-8 from socket import * # 1. 創(chuàng)建udp套接字 udp_socket = socket(AF_INET, SOCK_DGRAM) # 2. 準備接收方的地址 dest_addr = ('192.168.236.129', 8080) # 3. 從鍵盤獲取數(shù)據(jù) send_data = input("請輸入要發(fā)送的數(shù)據(jù):") # 4. 發(fā)送數(shù)據(jù)到指定的電腦上 udp_socket.sendto(send_data.encode('utf-8'), dest_addr) # 5. 等待接收對方發(fā)送的數(shù)據(jù) recv_data = udp_socket.recvfrom(1024) # 1024表示本次接收的最大字節(jié)數(shù) # 6. 顯示對方發(fā)送的數(shù)據(jù) # 接收到的數(shù)據(jù)recv_data是一個元組 # 第1個元素是對方發(fā)送的數(shù)據(jù) # 第2個元素是對方的ip和端口 print(recv_data[0].decode('gbk')) print(recv_data[1]) # 7. 關閉套接字 udp_socket.close()
python腳本:
網(wǎng)絡調試助手截圖:
更多關于Python相關內容可查看本站專題:《Python Socket編程技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
相關文章
詳解Python中的Numpy、SciPy、MatPlotLib安裝與配置
這篇文章主要介紹了詳解Python中的Numpy、SciPy、MatPlotLib安裝與配置,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11Python實現(xiàn)葵花8號衛(wèi)星數(shù)據(jù)自動下載實例
這篇文章主要為大家介紹了Python實現(xiàn)葵花8號衛(wèi)星數(shù)據(jù)自動下載實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10python scipy.spatial.distance 距離計算函數(shù) ?
本文主要介紹了python scipy.spatial.distance 距離計算函數(shù),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03