Home python Error connecting socket to server: A BYTES-LIKE OBJECT IS REQUIRED, NOT 'STR'

Error connecting socket to server: A BYTES-LIKE OBJECT IS REQUIRED, NOT ‘STR’

Author

Date

Category

Actually, error: Typeerror:

Awes-like Object IS Required, not ‘str’

Error in the line “SOCK.SEND (‘Hello, World”) “

Error was found in the client’s application, here’s the client code itself:

import socket
SOCK = Socket.Socket ()
SOCK.CONNECT (('Localhost', 9090))
SOCK.SEND ('Hello, World!')
Data = SOCK.RECV (1024)
SOCK.Close ()
Print (DATA)

Here is the server code:

import socket
SOCK = Socket.Socket ()
SOCK.BIND (('', 9090))
SOCK.LISTEN (1)
Conn, addr = sock.accept ()
Print ('Connected:', ADDR)
While True:
  Data = Conn.Recv (1024)
  If not data:
    Break
  Conn.send (Data.upper ())
Conn.Close ()

I wrote this example at all, because just (just a couple of minutes ago) began the study of sockets, and here it is.


Answer 1, Authority 100%

Socket.send method expects a sequence of bytes, not a string. To convert a string to a sequence of bytes, you can use the str.encode method:

sock.send ("Hello, World!". Encode ())

Similarly, if you want to get a non-sequence of bytes, but a string, you can use the str.decode method:

data = sock.recv (1024) .decode ()

By default, UTF-8 will be used as an encoding.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions