Writing a small battleship game server in Python

Mike Meyer mwm at mired.org
Fri Aug 12 20:55:30 EDT 2005


Michael Goettsche <mail at tuxipuxi.org> writes:

> On Thursday 11 August 2005 18:34, Dan wrote:
>> > The server should accept connections from new players and be able to
>> > handle multiple games concurrently.
>>
>> Multiple threads would be the way to go for a real application. But if
>> you want to avoid the complexity involved in threading and
>> synchronization in this exercize, you can avoid threads by using
>> "select" instead:
>>   http://www.python.org/doc/2.3.5/lib/module-select.html
>>
>> The "select" function allows you to determine (without blocking) which
>> sockets have input available.
>>
>> Python's "select" is a wrapper for the C function with the same name. On
>> Unix you can learn more about it using "man select".
>>
>
> Thanks Dan.
> Assuming the server accepts connections in an endless loop, how would I handle 
> communication without additional threads and create new games in that loop?
> Could you give me pseudo-code for this?

I recommended threads even more strongly than Dan did, so I'll answer
as well.

The pseudocode is:

while 1:
      (rd, wr, xl) = select(rl, wl, xl)
      for sock in rd:
          socketdict(sock).do_read()
      for sock in wr:
          socketdict(sock).do_write()
      for sock in xl:
          socketdict(sock).do_except()

Basically, you have objects that handle doing reads, writes, and
"other things". You create a new object every time you get a new
connection from your listennig socket, and store the object in
socketdict indexed by the socket. You may have different types of
objects in the dictionary, depending on what the socket is doing. In
particular, the socket that is doing an accept() will have an object
that creates new objects and stores them in the dictionary, whereas
other sockets aren't likely to need that capability.

When the objects socket has data ready to be read, it's do_read method
will be called. When the socket is ready for a write, it's do_write
method is called. When other conditions happen, it's do_except method
is called.

Those methods are pretty much the same whether you're using theads os
asynchronious IO. Two critical differences: the I/O to the sockets must
be done non-blocking, and you rally want to avoid operations that soak
up lots of real time.

There are frameworks around that already deal with all of this stuff
for you. Twisted comes to mind, but I've never used it, and it may no
be what I think it is.

   <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list