File size: 1,051 Bytes
7dec2b8
 
752afed
7dec2b8
b664970
 
7dec2b8
 
 
 
 
 
 
b664970
7dec2b8
 
 
 
 
 
 
 
 
 
 
 
b664970
7dec2b8
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# app.py
import os, socket, threading, sys

host = "0.0.0.0"
port = int(os.getenv("PORT", "5678"))

print("listening on", host, port)
print("hostname:", socket.gethostname())
try:
    print("local ips:", socket.gethostbyname_ex(socket.gethostname())[2])
except Exception as e:
    print("ip lookup error:", e)
sys.stdout.flush()

def handle_client(conn, addr):
    print("client connected:", addr)
    try:
        while True:
            data = conn.recv(1024)
            if not data:
                break
            print("received:", data.decode(errors="ignore").strip())
            conn.sendall(data)
    except Exception as err:
        print("error:", err)
    finally:
        conn.close()
        print("client disconnected:", addr)

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as srv:
    srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    srv.bind((host, port))
    srv.listen()
    while True:
        conn, addr = srv.accept()
        threading.Thread(target=handle_client, args=(conn, addr), daemon=True).start()