Kyu96
Kyu96

Reputation: 1349

Send byte sequence over python socket

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?

Upvotes: 0

Views: 2315

Answers (1)

Mark A
Mark A

Reputation: 948

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'))

Upvotes: 1

Related Questions