Skip to content Skip to sidebar Skip to footer

Sending And Receiving Arrays Via Sockets

Is it possible to send an array through UDP Sockets using Python? I am using Python 2.5 and trying to send a simple array but it's not working. It can send the array successfully b

Solution 1:

eval is doing something completely different than what you think.

To send data over network, you need to serialize it into an array of bytes, then deserialize it back. In Python, serialization of most objects can be done via pickle module:

if (UDPSock.sendto( pickle.dumps(a), addr)):

Deserialization:

data,addr = UDPSock.recvfrom(buf)
L = pickle.loads(data)
print repr(L) # prints array('i', [1, 3, 2])

Solution 2:

I would personally use tostring and fromstring since the built-in serialization methods are many times faster and pickle may not support NaN, Inf and other undefined values.


Solution 3:

You're trying to send a python object through a socket, it is normal that it doesn't work, you can't send objects in a socket, objects are not data, they are the representation of some data in a given programming language. You need to "translate" your object to data and re-create the object from the data on the other socket's side. One way to do this would be with the pickle module.

On the client side, you "pickle" the object:

data = pickle.dumps(my_array)

And on the server side, you "unpickle" the received data:

my_array = pickle.loads(received_data)

Solution 4:

You could try to pickle the array. Pickle is a python library to en- and decode python objects. It is able to do much more, but it is definitely sufficient to fulfill your task:

on the sender side you pickle the object to a string:

pickled_string = pickle.dumps(a)

on the receiver side you unpickle the object:

a = pickle.loads(received_string)
# a is now your sent array

Solution 5:

It has been a while since this question was asked, but I thought it's worth sharing the jsonsocket library. It makes it really easy to send strings, lists and dictionaries over sockets. It can handle big amounts of data efficiently. And you don't need to do any manual serialization/deserialization. Under the hood, it serializes the data as JSON strings on the client, and deserializes it on the server.


Post a Comment for "Sending And Receiving Arrays Via Sockets"