[英]Send and receive to/from a UDP socket python3.4
我有以下幾行代碼用於從python3.4中的UDP套接字發送和接收,其中我想將一個用戶的文件發送給另一個。 這是服務器端代碼:
...
data = file.read(1024)
n = int(fileSize / 1024) + 1
for i in range(n):
if(self.sock.sendto(data.encode(), ('127.0.0.1',int(self.nextUserPort)))):
print ("Sending ...")
data = file.read(1024)
print ("File has been Sent Completely!!!")
self.sock.sendto("END#".encode(), ('127.0.0.1',int(self.nextUserPort)))
這是客戶端代碼:
....
d = self.sock.recvfrom(1024)
data = d[0].decode()
addr = d[1]
try:
while (data.strip().find("END#") != 0) :
file.write(data.decode())
time1 = time.time()
data, addr = self.sock.recvfrom(1024)
time2 = time.time()
print ("download speed is "+ str(1.0/(time2-time1))+" kbps")
print ("File Downloaded Completely!!!!!")
except socket.timeout :
file.close()
self.sock.close()
但是當我運行代碼時,我得到了f(self.sock.sendto(data.encode(), ('127.0.0.1',int(self.nextUserPort))))
的以下錯誤:
AttributeError: 'bytes' object has no attribute 'encode'
當我刪除encode
我得到另一個錯誤,當我搜索它時,我得到必須在python3.4
中python3.4
進行編碼。
例外是告訴您問題出在哪里:
AttributeError:“字節”對象沒有屬性“編碼”
碰巧您要發送字節,因此無需在此行中進行任何轉換。
"END#".encode()
可以直接寫為b"END#"
。
與您的問題無關:您可能想使用TCP套接字或給傳輸一些邏輯以應對重新排序,丟失和重復的程序包。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.