import socket from transport.base import TransportBase class Transport(TransportBase): def __init__(self, config): super().__init__(config) self.listener = self.__connect(config['host'], config['port']) self.buffer = bytearray() def writeline(self, cmd_str): response_string = cmd_str + "\n" self.conn.sendall(bytes(response_string, 'utf-8')) def readline(self): data = self.conn.recv(16) # команды все короткие, нет смысла много читать из буфера # print('data: ', data) if not data: return '' line = self.__findLine(data) return line def close(self): self.listener.close() def __connect(self, host='127.0.0.1', port=12345): with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_listener: socket_listener.bind((host, port)) socket_listener.listen() conn, addr = socket_listener.accept() self.conn = conn return socket_listener def __findLine(self, data): data_chunk = bytearray(self.buffer) data_chunk.extend(data) # print("line: ", data_chunk) line_separator_index = data_chunk.find(b"\n") # print('n idx: ', line_separator_index) if line_separator_index > 0: line = data_chunk[0: line_separator_index] self.buffer = data_chunk[line_separator_index+1:] return line.decode('utf-8')