commit 239a7f825a840f863c5cd4f2dcbe093adc5a1105 Author: Eden Kirin Date: Fri Aug 11 09:32:11 2023 +0200 Initial version diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..722d5e7 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.vscode diff --git a/client.py b/client.py new file mode 100644 index 0000000..16d8f5d --- /dev/null +++ b/client.py @@ -0,0 +1,33 @@ +import socket +import uuid + + +HOST = "127.0.0.1" +PORT = 10000 + + +def main(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect((HOST, PORT)) + + n = 0 + client_uuid = uuid.uuid4() + + try: + while True: + message = f"[{client_uuid}] Hello world from client: {n}" + + sock.send(message.encode("ascii")) + rx_data = sock.recv(1024) + + print(f"RX: {rx_data.decode('ascii')}") + + n += 1 + except ConnectionError: + pass + + sock.close() + + +if __name__ == "__main__": + main() diff --git a/server.py b/server.py new file mode 100644 index 0000000..9b13870 --- /dev/null +++ b/server.py @@ -0,0 +1,51 @@ +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()