Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't close socket on KeyboardInterrupt

Tags:

python

sockets

from socket import socket, AF_INET, SOCK_STREAM

sock = socket(AF_INET, SOCK_STREAM)
sock.bind(("localhost", 7777))
sock.listen(1)
while True:
    try:
        connection, address = sock.accept()
        print("connected from " + address)
        received_message = sock.recv(300)
        if not received_message:
            break
        connection.sendall(b"hello")

    except KeyBoardInterrupt:
        connection.close()

so Im trying to wrap my head around sockets and have this pretty simple script but for some reason I can't kill this script with a KeyboardInterrupt

how do I do kill the script with a KeyboardInterrupt that and why can't I kill it with a KeyboardInterrupt?

like image 437
Zion Avatar asked Jan 19 '16 07:01

Zion


People also ask

How do I close a python socket?

You need to call shutdown() first and then close(), and shutdown takes an argument.

How do I disable KeyboardInterrupt in python?

How do I disable KeyboardInterrupt in Python? In the try block a infinite while loop prints following line- “Program is running”. On pressing ctrl + c, python interpretor detects an keyboard interrupt and halts the program mid execution. After that, finally block finishes its execution.

How do you handle KeyboardInterrupt?

In Python, there is no special syntax for the KeyboardInterrupt exception; it is handled in the usual try and except block. The code that potentially causes the problem is written inside the try block, and the 'raise' keyword is used to raise the exception, or the python interpreter raises it automatically.

What is keyboard interrupt error?

Keyboard Interrupt Error The KeyboardInterrupt exception is raised when you try to stop a running program by pressing ctrl+c or ctrl+z in a command line or interrupting the kernel in Jupyter Notebook.


3 Answers

  1. To break to get out the while loop. Without break, the loop will not end.
  2. To be safe, check whether connection is set.

from socket import socket, AF_INET, SOCK_STREAM

sock = socket(AF_INET, SOCK_STREAM)
sock.bind(("localhost", 7777))
sock.listen(1)
while True:
    connection = None # <---
    try:
        connection, address = sock.accept()
        print("connected from ", address)
        received_message = connection.recv(300)
        if not received_message:
            break
        connection.sendall(b"hello")
    except KeyboardInterrupt:
        if connection:  # <---
            connection.close()
        break  # <---

UPDATE

  • There was a typo: KeyBoardInterrupt should be KeyboardInterrupt.
  • sock.recv should be connection.recv.
like image 66
falsetru Avatar answered Oct 20 '22 13:10

falsetru


Try to use timeout to make the program periodically "jumps out" from the accept waiting process to receive KeyboardInterrupt command.

Here is an example of socket server:

import socket

host = "127.0.0.1"
port = 23333

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

sock.bind((host,port))
sock.listen()

sock.settimeout(0.5)

print("> Listening {}:{} ...".format(host,port))

try:
    while True:
        try:
            conn, addr = sock.accept()
            data = conn.recv(1024)
            if not data:
                print("x Client disconnected!")
                # break
            else:
                print("> Message from client: {}".format(data.decode()))
                msg = "> Message from server".format(data.decode()).encode()
                conn.sendall(msg)
        except socket.timeout:
            # print("Timeout")
            pass
        except KeyboardInterrupt:
            pass
except KeyboardInterrupt:
    print("Server closed with KeyboardInterrupt!")
    sock.close()
like image 20
Hansimov Avatar answered Oct 20 '22 15:10

Hansimov


Try adding a timeout to the socket, like so:

from socket import socket, AF_INET, SOCK_STREAM
sock = socket(AF_INET, SOCK_STREAM)
sock.bind(("localhost", 7777))
sock.settimeout(1.0)
sock.listen(1)
while True:
    try:
        connection, address = sock.accept()
        print("connected from " + address)
        received_message = sock.recv(300)
        if not received_message:
            break
        connection.sendall(b"hello")
    except IOError as msg:
        print(msg)
        continue    
    except KeyboardInterrupt:
        try:
            if connection:
                connection.close()
        except: pass
        break
sock.shutdown
sock.close()
like image 3
Rolf of Saxony Avatar answered Oct 20 '22 15:10

Rolf of Saxony