Reputation: 5
import socket
def Main():
host = '127.0.0.1'
port = 5001
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
message = input("-> ")
while message != 'q':
s.sendto (message, server)
data, addr = s.recvfrom(1024)
print ('Received from server: ' + (data))
message = input("-> ")
s.close()
if __name__ == '__main__':
Main()
When I run this code the line s.sendto (message, server)
causes a TypeError: a bytes-like object is required, not 'str'
.
How do you fix this kind of problem? I tried searching the internet but can't find a solution.
Upvotes: 0
Views: 2701
Reputation: 169
The error is due to the fact you are not encoding the message. Just change:
c.sendto(message, server)
to
c.sendto(message.encode(), server)
in your code.
Example:
import socket
s=socket.socket()
port=12345
s.bind(('',port))
print("Socket bind succesfully")
s.listen(5)
// note this point
message="This is message send to client "
while True:
c,addr=s.accept()
// here is error occured
c.send(message)
c.close()
This is will result in an error message:
c.send(message)
TypeError: a bytes-like object is required, not 'str'
and in order to fix it, we need to change:
c.send(message)
to
c.send(message.encode())
Upvotes: 1
Reputation: 29099
Sockets read and write bytes, not strings (that's a property of sockets in general, not a python-specific implementaiton choice). That's the reason for the error.
Strings have an encode()
methods that transforms them to byte-objects. So, instead of writing my_text
, write my_text.encode()
to your socket.
Similarly, when you read for the socket, you get a bytes-like object, on which you can call input_message.decode()
to convert it into string
Upvotes: 5