0
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.

2
  • Possible duplicate of How do I encode a string to bytes in the send method of a socket connection in one line? Commented Aug 16, 2018 at 15:53
  • @scraaappy that's not a good duplicate target; all the answers suggest prepending b to a string, but in this case the string is coming from user input, so prepending isn't possible. Explicitly encoding is better anyway - prepending b won't work if the string contains non-ascii characters. Commented Aug 17, 2018 at 4:49

2 Answers 2

5

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

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

2 Comments

Thank you for your help i did what you said and it solve the problem
@Firaga: thanks, please accept answer if it solves the problem
1

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())

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.