Initial version

This commit is contained in:
Eden Kirin
2023-08-11 09:32:11 +02:00
commit 239a7f825a
3 changed files with 85 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.vscode

33
client.py Normal file
View File

@ -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()

51
server.py Normal file
View File

@ -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()