MikeSmith
MikeSmith

Reputation: 11

"AttributeError: 'bytes' object has no attribute 'encode' "

I'm getting the following error while trying to run my code. Here is a snippet:

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...

The code runs for a couple of the iterations (usually at most 3, before crashing with the error mentioned above. I'm not too sure what's happening so any suggestion would be awesome, thanks!

Upvotes: 1

Views: 7697

Answers (1)

Billy
Billy

Reputation: 5609

It's probably something later in the code that is reassigning message to a bytes object - perhaps you're reassigning it the data received from the clientSocket? If so, the data returned the clientSocket is a bytes object and needs to be decoded, similarly to how you're using message.encode() to send text data through the client.

There's a pretty good explanation on the usage of bytes objects for IO communication - especially if you're used to the python2.x way of doing things - here

Upvotes: 1

Related Questions