P
Paul Pittlerson
I'm currently learning about the socket module. My question is how can I detect if a connection is closed from the other side, for example a KeyboardInterrupt as I frequently use. My code below:
##########################################################
#server script:
class client(threading.Thread):
def __init__(self, connection):
super(client, self).__init__()
self.recv = connection.recv
print dir(connection)
def start(self):
self.run()
def run(self):
while True:
data = self.recv(2000)
if data:
msg = self.decode(data)
print msg
#break;
def decode(self, data):
return pickle.loads(data)
class bullet_server:
def __init__(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start(self):
server_address = ("localhost", 9006)
print '/--server running--/'
print server_address
self.server.bind(server_address)
self.server.listen(5)
while True:
connection, client_address = self.server.accept()
c = client(connection)
c.start()
if __name__ == '__main__':
server = bullet_server()
server.start()
##########################################################
#client script:
# set IP and port
host = '127.0.0.1'
port = 9006
# connect to server
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((host, port))
def loop():
print 'Enter message:'
msg = raw_input()
encoded = pickle.dumps(msg)
connection.send(encoded)
loop()
loop()
##########################################################
#server script:
class client(threading.Thread):
def __init__(self, connection):
super(client, self).__init__()
self.recv = connection.recv
print dir(connection)
def start(self):
self.run()
def run(self):
while True:
data = self.recv(2000)
if data:
msg = self.decode(data)
print msg
#break;
def decode(self, data):
return pickle.loads(data)
class bullet_server:
def __init__(self):
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def start(self):
server_address = ("localhost", 9006)
print '/--server running--/'
print server_address
self.server.bind(server_address)
self.server.listen(5)
while True:
connection, client_address = self.server.accept()
c = client(connection)
c.start()
if __name__ == '__main__':
server = bullet_server()
server.start()
##########################################################
#client script:
# set IP and port
host = '127.0.0.1'
port = 9006
# connect to server
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect((host, port))
def loop():
print 'Enter message:'
msg = raw_input()
encoded = pickle.dumps(msg)
connection.send(encoded)
loop()
loop()