[Tutor] using sockets to send a list

Don Arnold Don Arnold" <darnold02@sprynet.com
Fri Feb 21 21:37:01 2003


----- Original Message -----
From: <am@fx.ro>
To: <tutor@python.org>
Sent: Friday, February 21, 2003 3:51 PM
Subject: [Tutor] using sockets to send a list


>
> Hello all!
>
>
> I am working on a networked cards game called "President". The
> server should be able to send some information to all the clients,
> using sockets.
>
> After experimenting a while, i have reached a dead end. It is
> possible that my approach is completely wrong  -  maybe there are
> other functions/modules and i am not aware of their existance.
>
>
> The information i need to send over the net is a list ( whose
> elements are dictionaries ):
>
> print self.players
>
> [{'name': 'gogu', 'lastcards': [], 'status': 0, 'cards': [(16, 0), (4, 0),
(5, 0
> ), (6, 0), (7, 0), (8, 0), (9, 0), (10, 0), (11, 0), (12, 0), (13, 0),
(14, 0),
> (15, 0), (3, 1), (4, 1), (5, 1), (6, 1), (15, 3)]}, {'name': 'gogu',
'lastcards'
> : [], 'status': 0, 'cards': [(7, 1), (8, 1), (9, 1), (10, 1), (11, 1),
(12, 1),
> (13, 1), (14, 1), (15, 1), (3, 2), (4, 2), (5, 2), (6, 2), (7, 2), (8, 2),
(9, 2
> ), (10, 2)]}, {'name': 'gogu', 'lastcards': [], 'status': 0, 'cards':
[(11, 2),
> (12, 2), (13, 2), (14, 2), (15, 2), (3, 3), (4, 3), (5, 3), (6, 3), (7,
3), (8,
> 3), (9, 3), (10, 3), (11, 3), (12, 3), (13, 3), (14, 3)]}]
>
>
> Here is what i've tried so far:
>
> 1. i have created the sockets,  using the 'socket' module.
>    Sending strings is working fine.
>
>
> 2. the list has to be converted somehow to a string before
>    sending it, right?
>
>    Is the 'pickle' module the right way to do this? or is there
>    another solution?
>

<snip the rest>

I don't know much (if anything) about sockets, but if you can send strings,
this might work (though it is kludgy):

1. Use the str() built in function to convert your data into a string
2. Send the string to the client
3. Receive the string on the client side into a buffer
4. Use exec() with string formatting to load the buffer back into a
variable.

 Here's the process simulated in the interpreter:

>>> a = [(1,2,3),{4: 'stuff'},[5,6]]
>>> aAsString = str(a)   ##this gets sent via the socket....
>>> buf = aAsString   ##imagine buffer is receiving its value from the
socket
>>> exec('b = %s' % buf)
>>> print b
[(1, 2, 3), {4: 'stuff'}, [5, 6]]

If I haven't mangled it too badly, your code might end up looking something
like this.

# SERVER:

def sendinfo(self,player):
   self.sockets[player].send(str(self.players),1024)

# CLIENT:

def getinfo(self):
   dst = self.sock.recv(1024)
   exec('self.players = %s' % dst)


HTH,
Don