Writing Multithreaded Client-Server in Python.

google at phaedro.com google at phaedro.com
Tue Aug 30 04:19:49 EDT 2005


Paul Rubin schreef:

> "Sidd" <iamsidd at gmail.com> writes:
> >    I tried finding and example of multithreaded client-serve program in
> > python. Can any one please tell me how to write a multithreaded
> > client-server programn in python such that
> > 1.It can handle multiple connections
> > 2.It uses actual threads and not select() or some other function
>
> If you mean multiple threads on the server side, see the SocketServer
> module and its ThreadingMixin class.  You may have to look at the
> source code since up until recently the docs were incomplete.  There
> is a big helpful comment at the top of SocketServer.py which recently
> got merged into the library reference manual.

Yes, however the term 'ThreadingMixIn' is a bit confusing (at least it
was to me).
What it does do, is handle each request (from the same client too) in a
new separate thread. Convenient if your processing intensive handle may
otherwise slow down the main server process becoming less responsive to
other requests.
What it doesn't do (and what Sidd seems to search as is suggested by
his 'select()' remark) is handle each client in a separate thread.

This is in fact listed in the (scarce) doc as a 'ToDo' of the
SocketServer if my memory serves me right.
If you want to apply SocketServer such that each client corresponds to
one thread that handles its' requests (and maintains its state), don't
use ThreadingMixIn - only the thread-selection will be executed in a
separate thread.
You could maintain a dictionary of Threads running RequestHandlers for
each client in the server class.
I use a new Handler for each incoming request, parse a username
parameter from the message and select the thread-handler from the
server dict. Each handler in the dict contains an open outgoing socket,
so I can also e.g. broadcast and notify clients.
Alternatively, you can (probably) keep the client2server socket open as
well (on both client and server). Thread selection should then
(hopefully :-) happen magically by calling the handle() method in each
thread directly.

HTH


Thijs




More information about the Python-list mailing list