“AttributeError:'bytes'对象没有属性'encode'”

时间:2016-11-14 14:55:12

标签: python python-3.x

尝试运行代码时出现以下错误。这是一个片段:

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次,然后在上面提到的错误崩溃之前。我不太确定发生了什么,所以任何建议都会很棒,谢谢!

1 个答案:

答案 0 :(得分:1)

这可能是代码中稍后会将message重新分配给bytes对象的内容 - 也许您正在重新分配从clientSocket收到的数据?如果是这样,返回的数据clientSocketbytes对象,需要decode d,类似于您使用message.encode()通过客户端发送文本数据的方式

对于bytes对象在IO通信中的使用有一个很好的解释 - 特别是如果你习惯了python2.x的做事方式 - here

相关问题