I'm playing around with sockets in python, just for the purpose of learning about them. However I am really annoyed with the following problem:
import socket
soc = socket.socket(socket.AF_INET)
soc.bind(('localhost',8000))
soc.listen(0)
client = soc.accept()
While the socket is waiting for a connection, pressing ctrl-c does not quit the application.
How can I quit the application?
A similar issue was addressed in these two questions, but there the accept
method was called from a separate thread and the problem was how to make ctrl-c kill that thread. Here the accept
method is called from the main thread.
Edit: I am running python 3.3.0 on Win7 64 bit.
I couldn't find a way to kill the application using ctrl-c
or any other way except for killing it through the task manager, so I wrote a workaround:
import socket,os
from threading import Thread
class socketListener(Thread):
def run(self):
soc = socket.socket(socket.AF_INET)
soc.bind(('localhost',8000))
soc.listen(0)
client = soc.accept()
pid = os.getpid()
sl = socketListener()
sl.start()
input('Socket is listening, press any key to abort...')
os.kill(pid,9)
This runs the script in a separate thread, while waiting for a keystroke in the main thread. Once the user presses a key, the entire application is killed.