Search code examples
pythonsocketsblocking

Python chatserver - Unable to close server because of blocking call


I'm writing a chat server in Python for an assignment. However, I am having an issue shutting down the server. Here's what's happening:

When a client connects, I spawn two threads: readThread and writeThread. readThread is responsible for reading data from the client and printing it to stdout, and writeThread is responsible for reading a message from stdin and sending it to the client.

When the client sends 'EXIT', I want to shutdown the server. My writeThread runs in a loop like this:

def write(self) :
        while self.dowrite :
            data = sys.stdin.readline().strip();            
            self.conn.send(data);
        print 'WriteThread loop ended';

Now, when I receive EXIT, I set dowrite to false, but, of course, that doesn't break the while loop because of the blocking call sys.stdin.readline().strip().

So, what happens is: to disconnect, the client needs to send EXIT, and then I need to hit return on the console. Is there any way I can work around this, so that when the client sends the exit message, I immediately break out of the while loop in write().

EDIT How it comes together:

The main thread spawns two threads : read and write, and then waits (joins) for read to finish. Read finishes when it reads EXIT. As soon as the read thread ends, the main thread continues and sets dowrite to false in the write thread, which should end the write loop, but that can only happen once the while loop iterates one more time.


Solution

  • Make child threads to be daemons:

    t.daemon = True
    

    Daemon threads will stop if your program exits.

    You could use an event to notify other threads about it. In the thread where the event occured:

    event.set() # event occurred
    

    In other threads:

    event.wait() # wait for event