[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [pygame] Network
On Mon, 10 Dec 2001, Leonardo Santagada wrote:
>I'm going to make it simple, how to do a networked game using python and
>pygame? Does I have to use sockets? Isn't there any easier(like pygame
>is to SDL) way to do it?
Use sockets.
They aren't very hard to use. This is some ugly code that can maybe be
used as a template for the connecting. Personally I'd go with pure and
simple ASCII data, unless you have huge performance needs (you'd be using
C/C++ in that case). Making each packet one ASCII line makes it easy to
debug, and not necessarily slower than some weird binary format that'll be
a real pita when you have to debug it.
The code below seems to work ok for me, but I'm of course open for flames.
Client:
# create the TCP socket
sock = socket (AF_INET, SOCK_STREAM)
# connect to the server
sock.connect ( ( host, 10000 ) )
# create a file
file = sock.makefile ()
# now we can read data from file using methods such as readline() on
# file. writing can be done by using the send() method on sock. To
# wait for data use select(), see below.
Server:
# create the TCP socket
s = socket (AF_INET, SOCK_STREAM)
# bind our socket for incoming requests
s.bind ( ( '', 10000 ) )
# listen for clients
s.listen ( 5 )
# perform the select that waits for an incoming client. We're only
# interested in incoming events. wait forever (set a last parameter if
# you want to timeout
incoming, out, ex = select.select ( [s], [], [])
# did we get a new incoming client?
if s in incoming:
# we have a new client on the socket
clientsocket, addr = s.accept ()
# now we can start serving the client
file = clientsocket.makefile ()
# read a line of ascii data
for line in file.readline ():
# handle the data somehow
handle ( line )
--
- "Remember -- that which does not kill us can only make us stronger."
- "And that which does kill us leaves us dead!"
-- Terry Pratchett, Carpe Jugulum
____________________________________
pygame mailing list
pygame-users@seul.org
http://pygame.seul.org