Python之UDP編程

來源:互聯網
上載者:User

標籤:%s   速度   get   image   發送   net   img   print   ref   

參考原文

  廖雪峰Python教程

 

TCP是建立可靠串連,並且通訊雙方都可以以流的形式發送資料。相對TCP,UDP則是面向不需連線的協議。 使用UDP協議時,不需要建立串連,只需要知道對方的IP地址和連接埠號碼,就可以直接發資料包。但是,能不能到達就不知道了。 雖然用UDP傳輸資料不可靠,但它 的優點是和TCP比,速度快,對於不要求可靠到達的資料,就可以使用UDP協議
服務端代碼
#匯入socket庫import socket#建立IPv4,UDP的sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#綁定連接埠:s.bind((‘127.0.0.1‘, 9999))#不需要開啟listen,直接接收所有的資料print(‘Bind UDP on 9999‘)while True:    #接收來自用戶端的資料,使用recvfrom    data, addr = s.recvfrom(1024)    print(‘Received from %s:%s.‘ % addr)    s.sendto(b‘hello, %s!‘ % data, addr)
用戶端代碼  
import sockets = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)#不需要建立串連:for data in [b‘Michael‘, b‘ALice‘, b‘FF‘]:    #發送資料到用戶端:    s.sendto(data, (‘127.0.0.1‘, 9999))    #接收來自用戶端的資料:    print(s.recvfrom(1024)[0].decode(‘utf-8‘))s.close()    
示範效果

 

Python之UDP編程

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.