From fae0c2ca1055e2c94299d16b12a20e84fbae1845 Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 22 Apr 2019 19:02:27 +0400 Subject: =?UTF-8?q?WIP:=20=D0=A7=D0=B5=D1=82=D0=B2=D0=B5=D1=80=D1=82=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B4=D0=B5=D0=BD=D1=8C,=20=D1=87=D0=B5=D1=82=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D1=82=D0=B0=D1=8F=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day4/task4/server.py | 110 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 day4/task4/server.py (limited to 'day4/task4/server.py') diff --git a/day4/task4/server.py b/day4/task4/server.py new file mode 100644 index 0000000..980eebc --- /dev/null +++ b/day4/task4/server.py @@ -0,0 +1,110 @@ +import socket +import struct +import json + + +def pack_str(data: str): + encoded = data.encode() + return struct.pack('I', len(encoded)) + encoded + + +def pack_bytes(data: bytes): + return struct.pack('I', len(data)) + data + + +def handle_request(data, connection): + request = json.loads(data) + + # Хотя метод только один, но все равно лучше + # сразу написать расширяемое приложение + if request['method'] == 'get': + path = request['path'] + + try: + with open(path, 'rb') as f: + file_data = f.read() + + except FileNotFoundError: + header = json.dumps({'status': 1, 'reason': 'Файл не найден'}) + connection.sendall(pack_str(header)) + + except PermissionError: + header = json.dumps({'status': 1, 'reason': 'Файл не доступен для чтения'}) + connection.sendall(pack_str(header)) + + # Я знаю, что это плохо, но сервер не должен падать, + # а других ошибок я не смог вспомнить + except Exception as e: + header = json.dumps({'status': 2, 'reason': str(e)}) + connection.sendall(pack_str(header)) + + else: + length = len(file_data) + header = json.dumps({'status': 0, 'size': length, 'path': request['path']}) + connection.sendall(pack_str(header)) + i = 0 + while i < length: + packet = pack_bytes(file_data[i: i + CHUNK_SIZE]) + connection.sendall(packet) + i += CHUNK_SIZE + + +def get_data(connection): + buffer = b'' + while len(buffer) < 4: + data = connection.recv(4 - len(buffer)) + if not data: + raise ConnectionError('Connection was closed') + + buffer += data + + size_packed, buffer = buffer[:4], buffer[4:] + if not size_packed: + raise ConnectionError('Connection was closed') + + (size,) = struct.unpack('I', size_packed) + data = connection.recv(size - len(buffer)) + return buffer + data + + +def handle_connection(connection, address): + while True: + try: + data = get_data(connection) + + except ConnectionResetError: + print(f'Connection with {address[0]} was unexpectedly closed') + break + + except ConnectionError: + print(f'Connection with {address[0]} was ended') + break + + except KeyboardInterrupt: + raise KeyboardInterrupt() + + else: + if not data: + print(f'Connection with {address[0]} was ended') + break + handle_request(data.decode(), connection) + + +HOST, PORT = ADDR = '0.0.0.0', 6000 +CHUNK_SIZE = 4096 +sock = socket.socket() +sock.bind(ADDR) +sock.listen(5) + +while True: + print('Listening for new connections...') + try: + connection, address = sock.accept() + print(f'Got a connection from {address[0]}') + handle_connection(connection, address) + + except KeyboardInterrupt: + print('Stopping server...') + sock.close() + print('Server stopped') + break -- cgit v1.2.3 From 7e591a381db30bfcd374ebdffdc058f8bbfd24ed Mon Sep 17 00:00:00 2001 From: Andrew Date: Mon, 22 Apr 2019 21:00:47 +0400 Subject: =?UTF-8?q?=D0=A7=D0=B5=D1=82=D0=B2=D0=B5=D1=80=D1=82=D0=B0=D1=8F?= =?UTF-8?q?=20=D0=B7=D0=B0=D0=B4=D0=B0=D1=87=D0=B0=20=D0=B7=D0=B0=D0=B2?= =?UTF-8?q?=D0=B5=D1=80=D1=88=D0=B5=D0=BD=D0=B0.=20=D0=98=D1=81=D0=BF?= =?UTF-8?q?=D0=BE=D0=BB=D1=8C=D0=B7=D1=83=D0=B5=D1=82=D1=81=D1=8F=20=D0=BD?= =?UTF-8?q?=D0=B5=20=D0=BE=D0=B1=D1=8F=D0=B7=D0=B0=D1=82=D0=B5=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F=20=D0=B1=D0=B8=D0=B1=D0=BB=D0=B8=D0=BE=D1=82?= =?UTF-8?q?=D0=B5=D0=BA=D0=B0=20tqdm=20(=D1=87=D1=82=D0=BE=D0=B1=D1=8B=20?= =?UTF-8?q?=D0=B1=D1=8B=D0=BB=D0=BE=20=D0=BA=D1=80=D0=B0=D1=81=D0=B8=D0=B2?= =?UTF-8?q?=D0=BE)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day4/task4/server.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'day4/task4/server.py') diff --git a/day4/task4/server.py b/day4/task4/server.py index 980eebc..fb88629 100644 --- a/day4/task4/server.py +++ b/day4/task4/server.py @@ -35,18 +35,21 @@ def handle_request(data, connection): # Я знаю, что это плохо, но сервер не должен падать, # а других ошибок я не смог вспомнить except Exception as e: - header = json.dumps({'status': 2, 'reason': str(e)}) + header = json.dumps({'status': 2, 'reason': f'{type(e)}: {e}'}) connection.sendall(pack_str(header)) else: length = len(file_data) header = json.dumps({'status': 0, 'size': length, 'path': request['path']}) connection.sendall(pack_str(header)) + print(f'Started sending file of size {length} bytes...') i = 0 while i < length: packet = pack_bytes(file_data[i: i + CHUNK_SIZE]) connection.sendall(packet) i += CHUNK_SIZE + print(i / length * 100, '%') + print(f'Transmission ended') def get_data(connection): @@ -91,7 +94,7 @@ def handle_connection(connection, address): HOST, PORT = ADDR = '0.0.0.0', 6000 -CHUNK_SIZE = 4096 +CHUNK_SIZE = 4096000 sock = socket.socket() sock.bind(ADDR) sock.listen(5) @@ -103,6 +106,9 @@ while True: print(f'Got a connection from {address[0]}') handle_connection(connection, address) + except ConnectionResetError: + print(f'Connection with {address[0]} was unexpectedly closed') + except KeyboardInterrupt: print('Stopping server...') sock.close() -- cgit v1.2.3 From 7f2e25edde7c4e8bc60514156abf28014a3f0c3c Mon Sep 17 00:00:00 2001 From: Andrew Date: Wed, 24 Apr 2019 20:48:19 +0400 Subject: =?UTF-8?q?=D0=94=D0=B5=D0=B9=D1=81=D1=82=D0=B2=D1=83=D1=8E=20?= =?UTF-8?q?=D0=BD=D0=B0=20=D0=BE=D0=BF=D0=B5=D1=80=D0=B5=D0=B6=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D0=B5,=20=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D0=BB=20=D0=B2=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD=D1=8B=D0=B5?= =?UTF-8?q?=20=D0=BF=D1=80=D0=BE=D1=81=D1=87=D0=B5=D1=82=D1=8B=20=D0=B8=20?= =?UTF-8?q?=D1=83=D0=B4=D0=B0=D0=BB=D0=B8=D0=BB=20=D0=BA=D0=BB=D0=B8=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=20=D0=BD=D0=B0=D0=BF=D0=B8=D1=81=D0=B0=D0=BD=D0=BD?= =?UTF-8?q?=D1=8B=D0=B9=20=D0=B2=20=D0=A1=D0=B8-=D1=81=D1=82=D0=B8=D0=BB?= =?UTF-8?q?=D0=B5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- day4/task4/server.py | 57 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 33 insertions(+), 24 deletions(-) (limited to 'day4/task4/server.py') diff --git a/day4/task4/server.py b/day4/task4/server.py index fb88629..d013b35 100644 --- a/day4/task4/server.py +++ b/day4/task4/server.py @@ -3,6 +3,11 @@ import struct import json +HOST, PORT = ADDR = '0.0.0.0', 6000 +CHUNK_SIZE = 4096000 +DATATYPE_SIZE = 4 # int + + def pack_str(data: str): encoded = data.encode() return struct.pack('I', len(encoded)) + encoded @@ -54,14 +59,15 @@ def handle_request(data, connection): def get_data(connection): buffer = b'' - while len(buffer) < 4: - data = connection.recv(4 - len(buffer)) + # Считываем размер пакета + while len(buffer) < DATATYPE_SIZE: + data = connection.recv(DATATYPE_SIZE - len(buffer)) if not data: raise ConnectionError('Connection was closed') buffer += data - size_packed, buffer = buffer[:4], buffer[4:] + size_packed, buffer = buffer[:DATATYPE_SIZE], buffer[DATATYPE_SIZE:] if not size_packed: raise ConnectionError('Connection was closed') @@ -93,24 +99,27 @@ def handle_connection(connection, address): handle_request(data.decode(), connection) -HOST, PORT = ADDR = '0.0.0.0', 6000 -CHUNK_SIZE = 4096000 -sock = socket.socket() -sock.bind(ADDR) -sock.listen(5) - -while True: - print('Listening for new connections...') - try: - connection, address = sock.accept() - print(f'Got a connection from {address[0]}') - handle_connection(connection, address) - - except ConnectionResetError: - print(f'Connection with {address[0]} was unexpectedly closed') - - except KeyboardInterrupt: - print('Stopping server...') - sock.close() - print('Server stopped') - break +def main(): + sock = socket.socket() + sock.bind(ADDR) + sock.listen(5) + + while True: + print('Listening for new connections...') + try: + connection, address = sock.accept() + print(f'Got a connection from {address[0]}') + handle_connection(connection, address) + + except ConnectionResetError: + print(f'Connection with {address[0]} was unexpectedly closed') + + except KeyboardInterrupt: + print('Stopping server...') + sock.close() + print('Server stopped') + break + + +if __name__ == '__main__': + main() -- cgit v1.2.3