Вопрос

Suppose I have 2 lists which are the x and y co-ordinates of points. Now I want to send the 2 lists through sockets to other computers on a network. Because I want to send lists, I append the lists in a list to form a list of lists and then send the data.

1.As they are lists, do I need to pickle them?

2.At the receiver's side how do I unpickle the lists and store the values in 2 different lists?

The example illustrating the situation is given below:

listx=[1,2,3]
listy=[4,5,6]
list_to_send.append(listx)
list_to_send.append(listy)
print list_to_send=>[[1,2,3],[4,5,6]]

Send the list to the reciever

At the receiver:

a=socket.recv(1024)

Now how to unpickle and differentiate the lists?

Это было полезно?

Решение

A better alternative would be some structure like JSON. Pickle-ing is a good option, but out of the box, its not much secure. (I will put up a link here about this, shortly). Also I am assuming your question is more about serialising/deserialising than TCP socket.

>>> import json
>>> list_to_send = []
>>> listx=[1,2,3]
>>> listy=[4,5,6]
>>> list_to_send.append(listx)
>>> list_to_send.append(listy)
>>> json.dumps(list_to_send)
'[[1, 2, 3], [4, 5, 6]]'
>>> msg = json.dumps(list_to_send)
>>> sendOverSocket(msg)

And on the receiver side:

>>> msg = receiveFromSocket()
>>> list_received = json.loads(msg)

I have left out the implementations of socket specific functions above.


Now to answer your question:

1.As they are lists, do I need to pickle them?

Yes, any object that you send over the wire needs to be serialised. Pickle or JSONify it, your call.

2.At the receiver's side how do I unpickle the lists and store the values in 2 different lists?

Use json.loads(..) as above, or pickle specific function. In the code above, list_received[0] will be the first list, list_received[1] will be the second list and so on..

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top