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

43 lines
1.4 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.

# udp_client.py
import socket
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
def run_udp_client():
"""UDP клиент - подключение без установки соединения"""
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 10001
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client_socket:
# UDP не требует connect(), но можно вызвать для удобства
# client_socket.connect((SERVER_HOST, SERVER_PORT))
messages = [
"Hello UDP Server!",
"UDP быстрее, но ненадежнее",
"EXIT"
]
for message in messages:
logging.info(f"📤 Отправка UDP: {message}")
# Отправляем дейтаграмму
client_socket.sendto(message.encode('utf-8'), (SERVER_HOST, SERVER_PORT))
# Получаем ответ (с таймаутом)
client_socket.settimeout(2)
try:
response, server_address = client_socket.recvfrom(1024)
logging.info(f"📥 Ответ: {response.decode('utf-8')}")
except socket.timeout:
logging.warning("⚠️ Таймаут: ответ не получен")
import time
time.sleep(1)
if __name__ == '__main__':
run_udp_client()