3laba/tcp_server.py
2026-05-08 11:23:10 +03:00

58 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import socket
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def run_tcp_server():
HOST = '127.0.0.1'
PORT = 10000
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_socket.listen(5)
print(f"SERVER: TCP сервер запущен на {HOST}:{PORT}")
print("SERVER: Ожидание подключений...")
print("SERVER: Нажмите Ctrl+C для остановки\n")
try:
while True:
client_socket, client_address = server_socket.accept()
print(f"SERVER: Клиент {client_address} подключился")
try:
while True:
data = client_socket.recv(1024)
if not data:
print(f"SERVER: Клиент {client_address} отключился")
break
received_text = data.decode('utf-8')
print(f"SERVER: Получено '{received_text}' от {client_address}")
modified_data = data.upper()
client_socket.sendall(modified_data)
print(f"SERVER: Отправлено '{modified_data.decode('utf-8')}'")
if modified_data == b'EXIT':
print(f"SERVER: Команда EXIT от {client_address}")
break
except ConnectionResetError:
print(f"SERVER: Клиент {client_address} разорвал соединение")
except Exception as e:
print(f"SERVER: Ошибка с {client_address}: {e}")
finally:
client_socket.close()
print(f"SERVER: Соединение с {client_address} закрыто\n")
except KeyboardInterrupt:
print("\nSERVER: Остановка сервера...")
if __name__ == '__main__':
run_tcp_server()