Python: interrupt s.accept ()

I have this code:

host, port = sys.argv[1:3]
port=int(port)
s = socket.socket()
s.bind((host,port))
s.listen(5)
while True:
    conn, addr = s.accept()
    threading.Thread(target=handle,args=(conn,)).start()

      

I need to stop my code with Ctrl-C, but Python doesn't get Ctrl-C when it waits for a new connection ( s.accept()

). How can I solve this problem?

0


source to share


2 answers


To stop a socket connection, you can call the method shutdown

like this:

s.shutdown(socket.SHUT_WR)

      



(This SHUT_WR stops all new writes and reads)

However, while your code is running, it pauses trying to make a TCP connection. To stop it with Ctrl-C, you need to start the socket on a different thread, giving the main thread the ability to wake up before the interrupt and send a disconnect message.

+1


source


You can use shutdown()

or close()

for your needs

An excellent explanation (from the AIX 4.3 Communication Programming Concepts ) is given below



Once the socket is no longer needed, the caller can discard the socket by applying a close routine to the socket descriptor. If a trusted socket has data associated with it when closed, the system continues to attempt to transfer data. However, if the data is still not delivered, the system discards the data. If the application is not used for any pending data, it can use the shutdown routine on the socket until it is closed.

0


source







All Articles