def _handle_peer(self, client_socket): """ Method looks for the appropriate handler for a message, dispatches the request to an appropriate handler (function or method) for processing. """ print('Connected ' + str(client_socket.getpeername())) host, port = client_socket.getpeername() peer_connection = PeerConnection(host=host, port=port, socket=client_socket, peer_id=None, debug=False) try: # to implement msg_data = peer_connection.recv_data() print("Message data primljen: ", msg_data) #if msg_type: # msg_type = msg_type.lower() # self.handlers are message type handlers, hash table with function pointer #if msg_type not in self.handlers: # self.__debug( 'Handling peer msg: %s: %s' % (msg_type, msg_data) ) # self.handlers[ msg_type ]( peer_connection, msg_data ) except KeyboardInterrupt: pass print('Disconnecting ' + str(client_socket.getpeername())) peer_connection.close()
def check_live_peers(self): """ Attempts to ping all known peers to ensure that they are still active. If they are not active remove from list --> Simple stabilizer. """ to_delete = [] # loop over peers and send msg PING for p_id in self.peers: is_active = False try: print('Check live %s' % p_id) host, port = self.peers[p_id] peer_connection = PeerConnection(p_id, host, port, debug=self.debug) peer_connection.senddata('PING', '') is_active = True except: to_delete.append(p_id) if is_active: peer_connection.close() # acquire lock to delete non active peers self.peer_lock.acquire() try: for p_id in to_delete: if p_id in self.peers: del self.peers[p_id] except: pass
def connect(self): # print self.peer_list connected_peers = [] for peer in self.peer_list: peer_connection = PeerConnection(self.peer_id, peer, self.info_hash) if peer_connection.is_connected(): connected_peers.append(peer_connection) peer_connection.run() logging.debug("{} peer(s) connected for".format(len(connected_peers))) return connected_peers