0

I am implementing a socket server in python. Everything works well except KeyboardInterrupt does not stop my server in the terminal. Any ideas? Thank a lot!

    def run(self) -> None:
        try:
            self.socket.listen()
            print(f'$ - Server {self.host}:{self.port} is running.')
            while True:
                client, address = self.socket.accept()
                Thread(target=clientHandler, args=[client, address]).start()
        except KeyboardInterrupt:
            print('! - Server interrupted.')

when ctrl+c is pressed it should stop the server but it does not

Taras Z
  • 1
  • 2
  • Does this answer your question? [can't close socket on KeyboardInterrupt](https://stackoverflow.com/questions/34871191/cant-close-socket-on-keyboardinterrupt) – Axe319 Jan 20 '23 at 16:15
  • No, that's a different question. The problem there is that the `try except ` clause is inside the `while True` loop. mine is not. But thank you – Taras Z Jan 20 '23 at 16:54
  • The underlying problem is that is `socket.accept` is blocking. Having it timeout occasionally _should_ allow you to `KeyboardInterrupt`. Where the `try`/`except` block is, doesn't really matter in this case. All you need is to set something like `self.socket.settimeout(.5)` and handle the timeout in a `try`,`except socket.timeout: pass` within your `while` loop. – Axe319 Jan 20 '23 at 20:49

0 Answers0