[Tutor] using sockets to send a list
am@fx.ro
am@fx.ro
Fri Feb 21 15:02:15 2003
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?
3. starting from the examples found in the reference manual for pickle,
i have tried to adapt them and here is the result
# SERVER:
def sendinfo(self,player):
src=StringIO()
p=pickle.Pickler(src)
p.dump(self.players)
self.sockets[player].send(src.getvalue(),1024)
# CLIENT:
def getinfo(self):
dst = StringIO(self.sock.recv(1024))
up = pickle.Unpickler(dst)
self.players=up.load()
Errors:
- server: self.sockets[player].send(src.getvalue(),1024)
socket.error: (22, 'Invalid argument')
( i guess it doesn't like src.getvalue() ... ? )
- client: File "client.py", line 111, in getinfo
self.players=up.load_list()
File "/usr/lib/python1.5/pickle.py", line 591, in load_list
k = self.marker()
File "/usr/lib/python1.5/pickle.py", line 500, in marker
stack = self.stack
AttributeError: stack
( at least it realises that it's a list : it uses load_list )
Any ideas?
Maybe i shouldn't use StringIO at all, but attach the (Un)Pickler
directly to the socket?
Thank you.
--
Adrian Maier
(am@fx.ro)