def new_client(): """ Start a new connection to server. """ client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) client.connect((IP, PORT)) logger.info(f'Client connection established at ({IP}: {PORT}).') return client
def listen(self): """ Listening server. """ while True: try: data = self.client.recv(BUF_SIZE) logger.info(f'Server received {data}, from {self.client}') self.client.sendall(f'Server received {data}'.encode()) if data == b'': raise Exception('Empty received.') except: self.client.close() self.foo() # traceback.print_exc() break
def listen(): logger.info('Client starts listening.') while True: try: data = client.recv(BUF_SIZE) logger.info(f'Client received {data}') if data == b'': raise Exception('Empty received.') except: logger.info(f'Client connection lost.') shutdown() break logger.info('Client stopped listening.')
shutdown() try: client = new_client() t = threading.Thread(target=listen) t.start() except Exception: traceback.print_exc() continue # Send msg[2:] to server, # if there is a valid connection if msg.startswith('s '): msg = msg[2:] try: client.sendall(msg.encode()) logger.info(f'Client send {msg}') time.sleep(0.5) except Exception: traceback.print_exc() continue # Shutdown current connection if msg == 'k': shutdown() continue # Quit if msg == 'q': shutdown() break
def accept_client(self): """ Start server by accepting new client connection """ logger.info('Server starts listening.') client, address = self.server.accept() logger.info(f'Connection established: {client}') return client