Skip to content Skip to sidebar Skip to footer

Typeerror: A Bytes-like Object Is Required, Not 'str' When Writing To A File

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)

Solution 1:

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

Solution 2:

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 objectis required, not'str'

and in order to fix it, we need to change:

c.send(message)

to

c.send(message.encode())

Post a Comment for "Typeerror: A Bytes-like Object Is Required, Not 'str' When Writing To A File"