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

2024-10-05 11:00:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在运行代码时遇到以下错误。以下是一个片段:

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


Tags: piptheto代码fromimportmessagefor
1条回答
网友
1楼 · 发布于 2024-10-05 11:00:37

这可能是代码中稍后将message重新分配给bytes对象的某些内容—可能是您将从clientSocket接收到的数据重新分配给它?如果是,返回的数据clientSocket是一个bytes对象,需要是decoded,类似于使用message.encode()通过客户端发送文本数据的方式。

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

相关问题 更多 >

    热门问题