-1

I wrote a server on python:

import  socket
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 8820))

server_socket.listen(1)

(client_socket, client_address) = server_socket.accept()

client_name = client_socket.recv(1024)
client_socket.send('Hello ' + client_name)

client_socket.close()
server_socket.close()

And, I wrote a client:

import socket

my_socket = socket.socket()
my_socket.connect(('127.0.0.1', 8820))

my_socket.send('Sami')
data = my_socket.recv(1024)
print('The server sent: ' + data)

my_socket.close()

But when I run the codes, in the server I get the error: "must be str, not bytes" and in the client I get the error: "a bytes-like object is required, not 'str'".

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
AmitaiF
  • 19
  • 2
  • 3
  • 2
    You are mixing your `str` typing and your `bytes` typing. When you send data you should be sending `bytes` when you are printing it out they should be `str` – MooingRawr Apr 03 '18 at 20:37
  • So how should I do it? – AmitaiF Apr 03 '18 at 20:37
  • 2
    Possible duplicate of [What is the difference between a string and a byte string?](https://stackoverflow.com/questions/6224052/what-is-the-difference-between-a-string-and-a-byte-string) – Fred Larson Apr 03 '18 at 20:38
  • Please tag your major Python version (2 or 3). – wim Apr 03 '18 at 20:39
  • @AmitaiF if you are using python 3, refer to https://stackoverflow.com/questions/7585435/best-way-to-convert-string-to-bytes-in-python-3 for methods to convert from bytes to string and viceversa. – Davide Visentin Apr 03 '18 at 20:42

2 Answers2

2

Use encode/decode to convert between str and bytes before sending and after receiving:

my_socket.send('Sami'.encode('utf-8'))  # encode string before sending
data = my_socket.recv(1024).decode('utf-8')  # decode string after receiving

You can replace 'utf-8' with other character encodings depending on your use case (you might see 'cp1252' used in Windows applications, for instance).

For the server, rather than decoding the string and encoding it again after putting 'Hello ' on the front, you can skip a step and do this:

client_name = client_socket.recv(1024)
client_socket.send(b'Hello ' + client_name)

b'Hello' is a literal bytes object, rather than a str object like 'Hello'. So b'Hello' + client_name will do bytes + bytes = bytes directly, rather than converting client_name to str with .decode, adding 'Hello' to get another str and then converting back to bytes with .encode.

a spaghetto
  • 1,072
  • 2
  • 14
  • 22
0

You need to encode before sending a string. Example:

mySocket.send("Hello".encode() + Client_name.encode())

Or:

mySocket.send(b"Hello" + Client_name.encode())
user4157124
  • 2,809
  • 13
  • 27
  • 42