[Tutor] UDP client

Phil phil_lor at bigpond.com
Sun Feb 26 01:44:22 EST 2017


Thank you for reading this.

As an exercise, and for no other purpose, I'm trying to convert some C++ 
code that I put together 17 years ago. I'm very rusty and hours of 
Internet searches have made me more confused that I was to start with.

The following works under Python2 but not under Python3.

import socket

host = "127.0.0.1"
#host = "localhost"

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

s.connect((host, 1210))

data = "GET_LIST"

s.sendall(data)

#s.sendto(data, (host, 1210))

s.shutdown(1)

while 1:
     buf = s.recv(2048)
     if not len(buf):
         break
     #print "Received: %s" % buf

According to the Python3 wiki sendto() should work under Python3 but I 
get this error:

Traceback (most recent call last):
   File "/home/phil/Python/predict_client1.py", line 12, in <module>
     s.sendall(data)
TypeError: a bytes-like object is required, not 'str'

The same error is received if I use sendall(data).

So, is this reasonable UDP client code and what have I overlooked to get 
this to work under Python3?

-- 
Regards,
Phil


More information about the Tutor mailing list