利用Python中的socket模塊中的來(lái)實(shí)現(xiàn)UDP協(xié)議,這里寫(xiě)一個(gè)簡(jiǎn)單的服務(wù)器和客戶端。為了說(shuō)明網(wǎng)絡(luò)編程中UDP的應(yīng)用,這里就不寫(xiě)圖形化了,在兩臺(tái)電腦上分別打開(kāi)UDP的客戶端和服務(wù)端就可以了。
UDP:用戶數(shù)據(jù)報(bào)協(xié)議,是一個(gè)面向無(wú)連接的協(xié)議。采用該協(xié)議不需要兩個(gè)應(yīng)用程序先建立連接。UDP協(xié)議不提供差錯(cuò)恢復(fù),不能提供數(shù)據(jù)重傳,因此該協(xié)議傳輸數(shù)據(jù)安全性差。
客戶端
python3只能收發(fā)二進(jìn)制數(shù)據(jù),需要顯式轉(zhuǎn)碼
from socket import *host = '192.168.48.128' # 這是客戶端的電腦的ipport = 13141 #接口選擇大于10000的,避免沖突bufsize = 1024 #定義緩沖大小addr = (host,port) # 元祖形式udpClient = socket(AF_INET,SOCK_DGRAM) #創(chuàng)建客戶端while True: data = input('>>> ') if not data: break data = data.encode(encoding="utf-8") udpClient.sendto(data,addr) # 發(fā)送數(shù)據(jù) data,addr = udpClient.recvfrom(bufsize) #接收數(shù)據(jù)和返回地址 print(data.decode(encoding="utf-8"),'from',addr)udpClient.close()服務(wù)器
同樣需要顯式轉(zhuǎn)碼
from socket import *from time import ctimehost = '' #監(jiān)聽(tīng)所有的ipport = 13141 #接口必須一致bufsize = 1024addr = (host,port) udpServer = socket(AF_INET,SOCK_DGRAM)udpServer.bind(addr) #開(kāi)始監(jiān)聽(tīng)while True: print('Waiting for connection...') data,addr = udpServer.recvfrom(bufsize) #接收數(shù)據(jù)和返回地址 #處理數(shù)據(jù) data = data.decode(encoding='utf-8').upper() data = "at %s :%s"%(ctime(),data) udpServer.sendto(data.encode(encoding='utf-8'),addr) #發(fā)送數(shù)據(jù) print('...recevied from and return to :',addr)udpServer.close()以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選