def recv_file(sock, f, download_limit, buf_size=BUFFER_SIZE, progress_callback=None): """ Receive file from socket sock - socket f - file-like object download_limit - reeiving file size buf_size - receive buffer size progress_callback - callback function, called when a packet of data received. def progress_handler(sock, count) Return a count of received bytes """ total_bytes_received = 0 while (True): need_download = (download_limit - total_bytes_received) buffer = connutils.recv_buffer(sock, min(need_download, buf_size)) bytes_readed = len(buffer) if buffer: f.write(buffer) total_bytes_received += bytes_readed #Run callback if (progress_callback and hasattr(progress_callback, "__call__")): progress_callback(sock, total_bytes_received) if ((total_bytes_received == download_limit) or (bytes_readed < buf_size)): break return total_bytes_received
def send_request_blocking(self, sock, command_type, *args, **kwargs): """ Send command Return answer if successtype """ recv_buffer_size = 0 #make request structure if command_type == PROTOCOL_COMMAND_SIZE: # send size command command = MyCommandProtocol.size_request(*args) recv_buffer_size = self.calculate_datagram_size( MyCommandProtocol.SIZE_COMMAND_FILE) elif command_type == PROTOCOL_COMMAND_SEEK: recv_data_size = kwargs['recv_data_size'] command = MyCommandProtocol.seek_request(*args) recv_buffer_size = self.calculate_datagram_size( MyCommandProtocol.SIZE_COMMAND_DATA + recv_data_size) else: raise CommandProtocolException("Invalid command") is_received = False for i in range(self._repeat_count): # if send timeout go to next iteration try: with AlarmTimer(self._timeout): buffer = self.pack(command) connutils.send_buffer(sock, buffer) except TimeoutException: print("send timeout") continue try: with AlarmTimer(self._timeout): #receive timeout while True: buffer = connutils.recv_buffer(sock, recv_buffer_size) if not buffer: return buffer try: datagram_dict = self.unpack(buffer) is_received = True break except ProtocolError as e: print("Bad datagram received %s" % e) #pdb.set_trace() if is_received: break except TimeoutException: print("Receive timeout") continue if not is_received: raise TimeoutException("Command send timeout") command = datagram_dict['data'] # extract and return result if command_type == PROTOCOL_COMMAND_SIZE: filesize = MyCommandProtocol.unpack_file_command(command) return filesize elif command_type == PROTOCOL_COMMAND_SEEK: data = MyCommandProtocol.unpack_data_command(command) return data