array/list of sockets

Chris Angelico rosuav at gmail.com
Sat Oct 26 18:31:07 EDT 2013


On Sun, Oct 27, 2013 at 9:15 AM,  <theelder777 at gmail.com> wrote:
> Thank you for your quick replies. I am trying to implement a very simple multithreaded webserver in python. Is using an array of sockets (for different clients) the correct way to go?

Firstly, before you respond any more, please get off Google Groups.
You are omitting context, which makes threading (topic threading here,
distinct from threads of execution) difficult to follow. Get a news
reader like Thunderbird, or switch to email (python-list at python.org).
It will be greatly appreciated. :)

As to threading in Python... You don't normally need to maintain a
list of sockets; the easiest way would be to spin off a thread every
time a new connection happens. In pseudo-code:

def connection_thread(sock):
    while True:
        sock.recv(...)
        do stuff with what you got, maybe write to the socket

def acceptloop():
    sock = ... however you're creating your listening socket
    while True:
        newsock = sock.accept()
        create new thread, connection_thread, newsock

Each thread needs only care about its one socket.

Now, if you're creating a chat server, where anything that comes in on
one socket goes to all the others, then you'll need to maintain that
list (that's why I said "normally"). In that case, the easiest way
would probably be for connection_thread to register its socket when it
begins, and unregister it when it ends (using try/finally to help).

There are other ways to manage multiple sockets. You could maintain a
list of them all and react any time one is readable/writable, with
select(); I'm not sure how to do that in Python as I've never done so,
but there's a way. With that, you'd simply add sockets to the list
when accept() has something, and remove them when they're closed. But
you said you were threading.

ChrisA



More information about the Python-list mailing list