2016-11-14 64 views
0

我在嘗試運行我的代碼時遇到以下錯誤。這裏是一個片段:「AttributeError:'字節'對象沒有屬性'編碼'」

import time; 
from socket import* 
from pip._vendor.distlib.compat import raw_input 

pingCount = 0 
minTime = 0 
maxTime = 0 
counter = 0 
totalTime = 0 
message = 'test' 
packetsLost = 0 

#Sends 10 pingcounts as setup_testing_defaults 
while pingCount < 11: 
counter +=1 

#Creates a UDP Socket 
clientSocket = socket(AF_INET, SOCK_DGRAM) 

#Sets timeout value for each one to 1 second 
#The timeout function determines how long till it expires 
clientSocket.settimeout(1) 

#Creating the paramaters for sendTo 
#SendTo sends the ping to the socket 
clientSocket.sendto(message.encode("utf-8"),('127.0.0.1',12000))  

#time() yields the current time in milliseconds 
start = time.time() 

#Trying to print data received from the server 
try: #etc... 

的代碼運行的一對夫婦的迭代(通常爲3,與上面提到的錯誤而崩潰之前,我也不太清楚發生了什麼事,所以任何建議將是真棒, !感謝

+0

在while循環的第二次或第三次迭代, 'message'可能是一個'bytes'類型。當然,沒有編碼方法。 –

+0

此代碼適用於我。也許這是嘗試後的代碼? – Hugal31

+0

根據有關代碼未顯示錯誤的報告進行投票關閉。另外,你有一個縮進問題; 'while'命令後面的代碼需要另一個級別的縮進來實際包含在while循環中。沒有修改,你的代碼就會在那裏引發語法錯誤。 – jpmc26

回答

0

後來可能是東西被重新分配messagebytes對象的代碼 - 也許你重新分配它從clientSocket接收的數據如果是的話,返回的數據clientSocketbytes對象,需要?是decode d,類似於你如何使用message.encode()發送文本da通過客戶端。

有上bytes對象進行IO通信的使用率相當不錯的解釋 - 特別是如果你已經習慣了做事的方式python2.x - here

相關問題