summaryrefslogtreecommitdiff
path: root/day4/task3/server.py
diff options
context:
space:
mode:
Diffstat (limited to 'day4/task3/server.py')
-rw-r--r--day4/task3/server.py53
1 files changed, 33 insertions, 20 deletions
diff --git a/day4/task3/server.py b/day4/task3/server.py
index f4e5ebe..3aea050 100644
--- a/day4/task3/server.py
+++ b/day4/task3/server.py
@@ -6,6 +6,10 @@ import json
import time
+HOST, PORT = ADDR = '0.0.0.0', 6000
+DATATYPE_SIZE = 4 # int
+
+
def pack_data(data):
encoded = data.encode()
return struct.pack('I', len(encoded)) + encoded
@@ -28,14 +32,15 @@ def handle_request(data):
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')
@@ -68,20 +73,28 @@ def handle_connection(connection, address):
connection.sendall(response)
-HOST, PORT = ADDR = '0.0.0.0', 6000
-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
+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 KeyboardInterrupt:
+ print('Stopping server...')
+ sock.close()
+ print('Server stopped')
+ break
+
+
+if __name__ == '__main__':
+ success = db.init('otrs_error.log')
+ if not success:
+ print('Не удалось инициализировать базу данных. Завершаем работу...')
+ else:
+ main()