Clean closing socket with <ctrl+c>
This commit is contained in:
parent
9106fdd490
commit
78be5f0877
|
@ -0,0 +1,26 @@
|
|||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
testsocketclose.py
|
||||
|
||||
https://stackoverflow.com/q/32019274/6709630
|
||||
"""
|
||||
import signal, socket, sys, time
|
||||
|
||||
def handler(signum, frame):
|
||||
""" Catch <ctrl+c> signal for clean stop"""
|
||||
print('\nNice exit')
|
||||
connection.close()
|
||||
sys.exit(0)
|
||||
|
||||
signal.signal(signal.SIGINT, handler)
|
||||
|
||||
# Creation de la connection
|
||||
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
connection.bind(('localhost', 5555))
|
||||
connection.listen(5)
|
||||
|
||||
while 1:
|
||||
print("Socket open:\n{}\nExit with <ctrl+c>".format(connection))
|
||||
time.sleep(2)
|
Loading…
Reference in New Issue