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, clie
You need to encode before sending a string. Example:
mySocket.send("Hello".encode() + Client_name.encode())
Or:
mySocket.send(b"Hello" + Client_name.encode())
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
.