TypeError: a bytes-like object is required, not 'str'

Solution 1:

This code is good for Python 2. But in Python 3, results in bit encoding error. I was trying to make a simple TCP server and encountered the same problem. Encoding solves this. Try this with sendto command.

clientSocket.sendto(message.encode(),(serverName, serverPort))

Similarly you should use .decode() to receive the data on the UDP server side, if you want to print it exactly as it was sent.

Solution 2:

Encoding and decoding can solve this in Python 3:

Client Side:

>>> host='127.0.0.1'
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.connect((host,port))
>>> st='connection done'
>>> byt=st.encode()
>>> s.send(byt)
15
>>>

Server Side:

>>> host=''
>>> port=1337
>>> import socket
>>> s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
>>> s.bind((host,port))
>>> s.listen(1)
>>> conn ,addr=s.accept()
>>> data=conn.recv(2000)
>>> data.decode()
'connection done'
>>>