0

I am trying to write a very basic server (for experimenting purposes) that listens to incoming connections on a port and when a client connects send a custom byte sequence to the client. However I am prompted with a type exception:

TypeError: string argument without an encoding

import socket
import sys

HOST = '127.0.0.1'
PORT = 1337

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    s.bind((HOST, PORT))
except socket.error as msg:
    sys.exit()

s.listen(10)
conn, addr = s.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
s.send(bytes('\x01\x02\x03'))
s.close()

Do I need to tell the socket somehow to send it as ascii or what am I doing wrong?

2
  • You need to specify an encoding, like bytes('\x01\x02\x03', 'ascii') Commented Apr 26, 2019 at 16:22
  • s.send(b'\x01\x02\x03')? Commented Apr 26, 2019 at 16:34

1 Answer 1

1

The send method requires a "bytes-like" object, which it looks like you are trying to pass in but aren't using the bytes function properly.

If you have actual binary data, like in your example, you can just create the bytes object directly:

s.send(b'\x01\x02\x03')

If you have a string (which is not the same as bytes in Python), then you have to encode the string into bytes. This can be done with the bytes function but you have to tell it what encoding to use. Generally ASCII or UTF-8 is used.

s.send(bytes('Hello world', 'ascii'))
s.send(bytes('Hello world', 'utf-8'))
Sign up to request clarification or add additional context in comments.

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.