1

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!

4
  • On the second or third iteration of your while loop, message is probably a bytes type. Which of course, has no encode method. Commented Nov 14, 2016 at 15:00
  • This code works for me. Maybe it is the code after the try ? Commented Nov 14, 2016 at 15:01
  • Voting to close based on reports that the code in question does not exhibit the error. Additionally, you have an indentation problem; the code following the while command needs another level of indentation to actually be contained in the while loop. Without modification, you code will throw a syntax error there. Commented Nov 14, 2016 at 17:26
  • Some things to note: your raw_input seems wrong (i.e.: import from pip?)... if you're in Python 3, you should use input instead. Also, please include the actual stack trace, just your sample partial code is not enough to diagnose it. Commented Nov 15, 2016 at 15:53

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.