01-17-2010, 10:34 AM | #1 |
Using KeyboardInterrupt with Sockets
Hi, everyone.
I'm trying to write a Python server application which listens on a port, but I also want the server to be to be terminated by pressing Ctrl+C (also Ctrl+Z on Windows). I've tried using the KeyboardInterrupt exception handler to do this. It works fine with this program. Code:
# Proof of concept: exit on interrupt using KeyboardInterrupt exception import sys def test(): try: i = 0 while i < 100000000: print(i) i += 1 except KeyboardInterrupt: print('This is stupid...') sys.exit(0) test() Code:
""" Echo server to test interrupts """ import sys import socket class EchoServer: def __init__(self, port=1000): print(__doc__) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', port)) s.listen(1) conn, addr = s.accept() while 1: try: chunk = conn.recv(1024) print(chunk) conn.send(chunk) # I want the server to terminate when Ctrl-C/Z is pressed except KeyboardInterrupt: conn.close() sys.exit(0) conn.close() sys.exit(0) if __name__ == '__main__': EchoServer() Thanks.
__________________
Sam's Py |
|
01-17-2010, 04:14 PM | #2 |
Re: Using KeyboardInterrupt with Sockets
The difference between your two examples is that the first one is spinning whereas the second one probably blocks waiting for data in conn.recv(). If you connect a client and start sending a bunch of data, your exception will start working. Try setting your socket to non-blocking mode in order to busy-wait checking for both socket and keyboard input. I'm sure python provides something similar to select() in order to wait more efficiently.
__________________
EDuke32 - "The corrupt doctrine of terror has begun." |
|
01-22-2010, 05:41 AM | #4 |
Re: Using KeyboardInterrupt with Sockets
Thanks. I got it working in the end using Threads. http://vark.com/t/2981ec
__________________
Sam's Py |
|
Bookmarks |
Tags |
python |
|
|