diff options
Diffstat (limited to 'day4/task4/server.py')
| -rw-r--r-- | day4/task4/server.py | 57 |
1 files changed, 33 insertions, 24 deletions
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() |