Reputation: 619
Given this portion of code, when pressing Ctrl+C the program returns error "name 'sock' is not defined.". I guess this is normal since sock.close()
is outside the class, but what should I do to prevent it ?
In my case it is about a client, not server, that asks for socket close.
import socket
class something(object):
def connect(self):
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.tcp_ip, self.tcp_port))
# etc.
if __name__ == '__main__':
try:
app = something()
app.connect()
except KeyboardInterrupt:
pass
finally:
sock.close()
Upvotes: 1
Views: 3026
Reputation: 1339
For closing nicely a connection with <ctrl+c>
signal
may be used to catch keyboard interrupt:
#!/usr/bin/env python3
""" testsocketclose.py """
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)
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)
Upvotes: 0
Reputation: 5885
This should work I think
import socket
class something(object):
def __init__(self):
self.sock = None
def connect(self):
self.sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('127.0.0.1', 12397))
self.sock.recv(1024)
def close(self):
self.sock.close()
if __name__ == '__main__':
try:
sk = something()
sk.connect()
except KeyboardInterrupt:
pass
finally:
sk.close()
print "Socket Closed"
Upvotes: 2
Reputation: 582
Try this instead.
if __name__ == '__main__':
try:
foo = something()
foo.connect()
except KeyboardInterrupt:
pass
finally:
foo.sock.close()
Upvotes: -1