欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 網(wǎng)絡編程之UDP發(fā)送接收數(shù)據(jù)功能示例【基于socket套接字】

 更新時間:2019年10月11日 11:34:05   作者:houyanhua1  
這篇文章主要介紹了Python 網(wǎng)絡編程之UDP發(fā)送接收數(shù)據(jù)功能,結合實例形式分析了Python使用socket套接字實現(xiàn)基于UDP協(xié)議的數(shù)據(jù)發(fā)送端與接收端相關操作技巧,需要的朋友可以參考下

本文實例講述了Python 網(wǎng)絡編程之UDP發(fā)送接收數(shù)據(jù)功能。分享給大家供大家參考,具體如下:

demo.py(UDP發(fā)送數(shù)據(jù)):

import socket # 導入socket模塊
def main():
  # 創(chuàng)建一個udp套接字
  udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  # 綁定本機ip和端口號 (發(fā)送數(shù)據(jù)時,如果不綁定,系統(tǒng)會隨機分配端口號。接收數(shù)據(jù)時,一般需要手動綁定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類型
  # 關閉套接字
  udp_socket.close()
if __name__ == "__main__":
  main()

demo.py(UDP接收數(shù)據(jù)):

import socket
def main():
  # 1. 創(chuàng)建套接字
  udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  # 2. 綁定本機ip和端口
  udp_socket.bind(("", 7788)) # 綁定本機的ip和端口(元組類型) ""表示本機ip
  # 3. 用套接字接收數(shù)據(jù)
  recv_data = udp_socket.recvfrom(1024)  # 1024表示本次接收的最大字節(jié)數(shù)。會阻塞代碼,直到接收到數(shù)據(jù)
  # recv_data這個變量中存儲的是一個元組 (接收到的數(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. 關閉套接字
  udp_socket.close()
if __name__ == "__main__":
  main()

更多關于Python相關內(nèi)容可查看本站專題:《Python Socket編程技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設計有所幫助。

相關文章

最新評論