Добавлен server.py
This commit is contained in:
parent
ddc44b8412
commit
1e39501c23
71
main.py
Normal file
71
main.py
Normal file
|
|
@ -0,0 +1,71 @@
|
||||||
|
import socket
|
||||||
|
import threading
|
||||||
|
|
||||||
|
PORT = 5555
|
||||||
|
BIND_IP = "0.0.0.0"
|
||||||
|
|
||||||
|
clients = {}
|
||||||
|
|
||||||
|
def handle_client(client_socket):
|
||||||
|
current_client_id = None
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
header = client_socket.recv(8)
|
||||||
|
if not header or len(header) < 8:
|
||||||
|
break
|
||||||
|
|
||||||
|
version = header[0]
|
||||||
|
packet_type = header[1]
|
||||||
|
sender_id = int.from_bytes(header[2:5], byteorder='big')
|
||||||
|
receiver_id = int.from_bytes(header[5:8], byteorder='big')
|
||||||
|
|
||||||
|
if current_client_id is None:
|
||||||
|
current_client_id = sender_id
|
||||||
|
clients[current_client_id] = client_socket
|
||||||
|
print(f"[⇄ Сервер]: Клиент {current_client_id} зарегистрирован.")
|
||||||
|
|
||||||
|
meta = client_socket.recv(16)
|
||||||
|
if len(meta) < 16:
|
||||||
|
break
|
||||||
|
|
||||||
|
payload_len = int.from_bytes(meta[12:16], byteorder='big')
|
||||||
|
|
||||||
|
payload = b""
|
||||||
|
while len(payload) < payload_len:
|
||||||
|
chunk = client_socket.recv(payload_len - len(payload))
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
payload += chunk
|
||||||
|
|
||||||
|
full_packet = header + meta + payload
|
||||||
|
|
||||||
|
if packet_type == 0x03: # Костыль что-бы пакет авторегистрации бился в никуда
|
||||||
|
continue
|
||||||
|
|
||||||
|
if receiver_id in clients:
|
||||||
|
clients[receiver_id].sendall(full_packet)
|
||||||
|
print(f"[⇄ Маршрутизация]: Пакет {hex(packet_type)} от {sender_id} -> {receiver_id} переслан.")
|
||||||
|
else:
|
||||||
|
print(f"[⇄ Маршрутизация]: Получатель {receiver_id} оффлайн.")
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
if current_client_id in clients:
|
||||||
|
del clients[current_client_id]
|
||||||
|
client_socket.close()
|
||||||
|
print(f"[⇄ Сервер]: Клиент {current_client_id} отключился.")
|
||||||
|
|
||||||
|
def main():
|
||||||
|
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||||
|
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
server.bind((BIND_IP, PORT))
|
||||||
|
server.listen()
|
||||||
|
print(f"Запущен на {BIND_IP}:{PORT}...")
|
||||||
|
|
||||||
|
while True:
|
||||||
|
client_sock, _ = server.accept()
|
||||||
|
threading.Thread(target=handle_client, args=(client_sock,), daemon=True).start()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Loading…
Reference in a new issue