52 lines
1021 B
Python
52 lines
1021 B
Python
import socket
|
|
from _thread import start_new_thread
|
|
|
|
HOST = "127.0.0.1"
|
|
PORT = 10000
|
|
|
|
|
|
# threaded handler function
|
|
def handler(conn: socket.socket):
|
|
while True:
|
|
try:
|
|
rx_data = conn.recv(1024)
|
|
except ConnectionError:
|
|
print("Connection terminated")
|
|
break
|
|
|
|
if not rx_data:
|
|
print("Bye")
|
|
break
|
|
|
|
tx_data = f"ACK: {rx_data.decode('ascii')}"
|
|
|
|
conn.send(tx_data.encode("ascii"))
|
|
|
|
conn.close()
|
|
|
|
|
|
def main():
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
sock.bind((HOST, PORT))
|
|
print(f"Socket bound to port: {PORT}")
|
|
|
|
# listening mode
|
|
sock.listen()
|
|
print("Socket ready to accept connections")
|
|
|
|
try:
|
|
while True:
|
|
conn, addr = sock.accept()
|
|
|
|
print(f"Client connected to: {addr[0]}:{addr[1]}")
|
|
|
|
start_new_thread(handler, (conn,))
|
|
except (KeyboardInterrupt, SystemExit):
|
|
pass
|
|
|
|
sock.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|