TCP server as a Windows service using Python?

David Bolen db3l at
Fri Jan 30 22:53:26 CET 2004

David Mitchell <djmitchell at> writes:

> I can't see how to let the service accept *either* an incoming TCP client
> connection *or* an e.g. "stop service" message.  If someone could point me
> to some sample code, I'd greatly appreciate it - Google hasn't been
> helpful.

NT Services generally run a dedicated thread to handle service control
messages - normally the application starts up and lets its main thread
handle that, and it starts a secondary thread to actually run the
application code.

It's been a while since I last used it, but if you are using the
service support from win32all then I believe it should handle it
automatically for you.  If you subclass from
win32serviceutil.ServiceFramework, then the Svc* control message calls
(such as SvcStop) should, I believe, arriving in a different thread
from your main execution. (*)

Thus, your client side processing only has to wait for the TCP
connection.  The stop service connection is handled in the service
message thread, which the framework will turn into the method call.

Now, you do have to figure out how you want to interrupt your TCP
client processing when you get such a stop message.  The demo with
win32all uses an event which it can wait on along with the pipes.  You
could do the same thing with sockets if you used native Windows
operations, but if you're using more portable Python stuff, I'd
probably just have a periodic timeout to your select to check a flag,
or even have an internal loopback socket that you write to to wake up
the select and then it can shut down.

-- David

(*) If for some reason this isn't the case, you can still architect
your service this way - just spin off a new thread at startup to
handle your TCP clients.

More information about the Python-list mailing list