def get_needed_blocks(self): from PeerPack import db block_list = db.get_blocks(self.peer.file_hash) request_list = [] for i in range(self.last_index): if not block_list.__contains__(i + 1): request_list.append(i + 1) return request_list
def get_status(self): from PeerPack import db block_list = db.get_blocks(self.file_hash) block_ratio = block_list.__len__() / self.last_index body = 'EMPTY' status = '' if block_ratio < 0.9: status = 'DOWNLOAD_PHASE' body = self.get_needed_blocks() elif block_ratio < 1: status = 'LAST_PHASE' body = self.get_needed_blocks() elif block_ratio == 1: status = 'COMPLETE_PHASE' else: print('Send Status Error') return status, body
def recv_msg(self, buf_size=20000): from PeerPack import fm, db while True: try: msg = self.client_socket.recv(buf_size) print('Receive' + str(msg)) head, body, block_num = self.decode_msg(msg) my_block_list = db.get_blocks(self.peer.file_hash) if head == 'BLOCK': #block_num = msg['FOOT'] byte_data = binascii.unhexlify(body.encode('utf-8')) block = BlockVO.BlockVO(file_hash=self.peer.file_hash, file_path=self.file_path, block_num=block_num, block_data=byte_data) fm.insert_block(block) elif head == 'REQ': self.send_block(my_block_list, body) msg_dict = self.create_dict('QUIT', 'QUIT') self.send_msg(msg_dict) break elif head == 'QUIT': msg_dict = self.create_dict('QUIT', 'QUIT') self.send_msg(msg_dict) fm.request_write_blocks() quit_flag = self.request_to_dht() if quit_flag is True: break elif head == 'FINISH': msg_dict = self.create_dict('ASK', 'ASK') self.send_msg(msg_dict) else: status, body = self.get_status() self.send_status(status, body) except Exception as e: print('error'+str(e)) break
def recv_msg(self, buf_size=10000): from PeerPack import fm, db while True: try: msg = self.client_socket.recv(buf_size) print('Receive' + str(msg)) head, body = self.decode_msg(msg) my_block_list = db.get_blocks(self.file_hash) if head == 'BOOTSTRAP_PHASE': self.send_block(my_block_list) elif head == 'DOWNLOAD_PHASE': self.send_block(my_block_list, body) elif head == 'LAST_PHASE': self.send_block(my_block_list, body) elif head == 'COMPLETE_PHASE': break elif head == 'ASK': phase, request_block = self.get_status() if phase != 'COMPLETE_PHASE': msg_dict = self.create_dict('REQ', request_block) else: msg_dict = self.create_dict('QUIT', 'QUIT') self.send_msg(msg_dict) elif head == 'BLOCK': block_num = msg['FOOT'] byte_data = binascii.unhexlify(body.encode('utf-8')) block = BlockVO.BlockVO(file_hash=self.file_hash, file_path=self.file_path, block_num=block_num, block_data=byte_data) fm.insert_block(block) elif head == 'QUIT': fm.request_write_blocks() break except Exception as e: print(e) break