Reputation: 44345
Using sockets in python3.x
I want to send the content of a dictionary over a socket, which for some reasons is NOT answered by the link just above this line...
client.py:
a = {'test':1, 'dict':{1:2, 3:4}, 'list': [42, 16]}
bytes = foo(a)
sock.sendall(bytes)
server.py:
bytes = sock.recv()
a = bar(bytes)
print(a)
How to convert any dictionary to a sequence of bytes (to be able to be sent through a socket) and how to be converted back? I prefer a clean and simple way to do this.
What I have tried so far:
sock.sendall(json.dumps(data))
TypeError: 'str' does not support the buffer interface
sock.sendall(bytes(data, 'UTF-8'))
TypeError: encoding or errors without a string argument
data = sock.recv(100)
a= data.decode('UTF-8')
AttributeError: 'str' object has no attribute 'decode'
Upvotes: 4
Views: 13938
Reputation: 94891
This is primarily summarizing the comments, but you need to convert the dict to a json str
object, convert that str
object to a bytes
object by encoding it, and then send that over the socket. On the server-side, you need to decode the bytes
object sent over the socket back to a str
, and then use json.loads
to turn it back into a dict
.
Client:
b = json.dumps(a).encode('utf-8')
s.sendall(b)
Server:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 1234))
s.listen(1)
conn, addr = s.accept()
b = b''
while 1:
tmp = conn.recv(1024)
b += tmp
d = json.loads(b.decode('utf-8'))
print(d)
Upvotes: 12