Python Sockets Error Typeerror: a Bytes-Like Object Is Required, Not 'Str' with Send Function

TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3

You opened the file in binary mode:

with open(fname, 'rb') as f:

This means that all data read from the file is returned as bytes objects, not str. You cannot then use a string in a containment test:

if 'some-pattern' in tmp: continue

You'd have to use a bytes object to test against tmp instead:

if b'some-pattern' in tmp: continue

or open the file as a textfile instead by replacing the 'rb' mode with 'r'.

TypeError: a bytes-like object is required, not 'str' when I'm inputting command in console

This error is because python expects bytes not string to be sent via socket.

Hence you have to convert strings to bytes before sending that. you can use encode() to convert string to bytes and use decode() to convert bytes received into string.

I have updated your code, Please refer below, this should work fine.

import socket
HOST = '0.0.0.0'
PORT = 12345

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))

server_socket.listen(5)
print("\n[*] Listening on port " +str(PORT)+ ", waiting for connexions. ")

client_socket, (client_ip, client_port) = server_socket.accept()
print("[*] Client " +client_ip+ " connected \n")

while True:
try:
command = input(client_ip+ ">")
if(len(command.split()) != 0):
client_socket.send(command.encode('utf-8')) #Encoding required here

else:
continue

except(EOFError):
print("Invalid input, type 'help' to get a list of implented commands. \n")

continue

if(command == "quit"):
break

data = client_socket.recv(1024)
print(data.decode('utf-8') + "\n") #Decoding required here

client_socket.close()

python socket programming TypeError: bytes like object is required not str

While communicating in Python, you should encode the parameter you send as a byte and decode the parameter you received from the byte format. You can understand what I want to say from the code below.

Server Code:

import socket

def server(interface, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((interface, port))
sock.listen(1)
print('Listening at', sock.getsockname())
while True:
sc, sockname = sock.accept()
print('We have accepted a connection from', sockname)
print(' Socket name:', sc.getsockname())
print(' Socket peer:', sc.getpeername())
message = sc.recv(1024).decode('utf-8')
print(' Incoming sixteen-octet message:', repr(message))
sc.sendall(bytes('Farewell, client','utf-8'))
sc.close()
print(' Reply sent, socket closed')

if __name__ == '__main__':
server('0.0.0.0', 9999)

Client Code:

import socket

def client(host, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
print('Client has been assigned socket name', sock.getsockname())
command = input("message > ")
sock.sendall(bytes(command,'utf-8'))
reply = sock.recv(1024).decode('utf-8)
print('The server said', repr(reply))
sock.close()

if __name__ == '__main__':
client('localhost', 9999)

If you edit your code this way, I think you will correct the error you received. I hope it helps as I am new to this. Sorry for my entry-level English.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

Socket Programming - a bytes-like object is required, not 'str'

Simply like this

c.send(b'Thank you for connecting')

How can I remove 'TypeError: a bytes-like object is required, not 'str''

s.sendto(line.encode('utf8'), addr) will turn it into utf8 bytes(probably what you want)



Related Topics



Leave a reply



Submit