socket error: a bytes-like object is required, not str

1

I'm trying to make a chat in local mode using socket but it throws me the error when I enter the message to send:

Traceback (most recent call last):
  File "C:\Users\Angel\Desktop.py", line 8, in <module>
    s.send(mensaje,'rb')
TypeError: a bytes-like object is required, not 'str'

server.py code:

import socket

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(("",9999))
s.listen(1)

sc,addr = s.accept()

while True:
    recibido = sc.recv(1024)
    if recibido == 'close':
        break
    print(str(addr[0])+" dice: ",recibido)
    sc.send(recibido)
print("adios")
sc.close()
s.close()

client.py:

import socket

s = socket.socket()
s.connect(('192.168.8.100',9999))

while True:
    mensaje = input("Mensaje a enviar: ")
    s.send(mensaje,'rb')
    if mensaje == "close":
        break
print("adios")
s.close()
    
asked by Revsky01 10.10.2018 в 21:42
source

1 answer

1

If we review the documentation of send() , we see that the definition says ssocket.send(bytes[, flags]) , that is, the method expects an object bytes not% str . You can modify this call:

s.send(mensaje,'rb')

By:

s.send(mensaje.encode(),'rb')

encode() is a method of class str and returns the bytes corresponding to the string in the encoding passed by parameter, in this case, the default: utf-8 is used.

Lastly I commit you that recv() also returns an object bytes so the correct way to do the comparison would be using decode() , a method in this case of the object bytes , same as in the previous case, by not indicating anything will be used in the encoding utf-8 :

if recibido.decode() == 'close'
    
answered by 10.10.2018 / 22:07
source