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

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


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.


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


A bit of encoding can solve this:

Client Side:

message = input("->")clientSocket.sendto(message.encode('utf-8'), (address, port))

Server Side:

data = s.recv(1024)modifiedMessage, serverAddress = clientSocket.recvfrom(message.decode('utf-8'))