Stopping a socket.accept() method

Peter Hansen peter at engcorp.com
Mon Aug 16 01:25:27 EDT 2004


Tobias Pfeiffer wrote:

> I am writing a network game where the server runs in a console window. 
> The person who has opened the server shall be able to stop the process of 
> accepting new clients. By now, I am handling that like this:
> 
> while 1:
>     	try:
>     	    	bla = socket.accept()
>     	except KeyboardInterrupt:
>     	    	break
> socket.shutdown(2)
> 
> So the user can Ctrl+C and no more clients will be accepted. 
> Unfortunately, this doesn't work in Windows. So how can I give the user 
> the ability to quit the loop interactively? Any ideas?

Several options.

1. Ctrl-Break will work if it's a console program and Ctrl-C
doesn't.

2. You can use a non-blocking socket and select(), which
will allow a periodic wakeup to check a flag that is set
by whatever mechanism you want to tell the prog to stop.

3. Have another thread, which can detect the request to
stop, open a connection to the server thread's socket
so that it will wake up... then it can check a flag
and terminate as in 2.

-Peter



More information about the Python-list mailing list