From e066c3f29bffbb8bcce07dc1dbd48d50d0f75f59 Mon Sep 17 00:00:00 2001 From: TheGreyDiamond Date: Tue, 1 Sep 2020 17:24:11 +0200 Subject: [PATCH] First network --- Code/session.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/Code/session.py b/Code/session.py index e69de29..2c401e5 100644 --- a/Code/session.py +++ b/Code/session.py @@ -0,0 +1,61 @@ +import socket, time, asyncio, threading + +client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) # UDP +server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) + +# Enable port reusage so we will be able to run multiple clients and servers on single (host, port). +# Do not use socket.SO_REUSEADDR except you using linux(kernel<3.9): goto https://stackoverflow.com/questions/14388706/how-do-so-reuseaddr-and-so-reuseport-differ for more information. +# For linux hosts all sockets that want to share the same address and port combination must belong to processes that share the same effective user ID! +# So, on linux(kernel>=3.9) you have to run multiple servers and clients under one user to share the same (host, port). +# Thanks to @stevenreddie +# client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + +# Enable broadcasting mode +client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) +server.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) + +client.bind(("", 37020)) + + + +def serverMain(): + print("Server main started") + # Set a timeout so the socket does not block + # indefinitely when trying to receive data. + server.settimeout(0.2) + message = b"your very important message" + i = 0 + while i<=10: + server.sendto(message, ("", 37020)) + print(f"Sent at {time.strftime('%X')}") + print("message sent!") + time.sleep(1) + i+=1 + print("Server quited") + +def clientMain(): + print("Client started") + while True: + # Thanks @seym45 for a fix + data, addr = client.recvfrom(1024) + print("received message: %s" % data) + print(f"Rec at {time.strftime('%X')}") + print("Client quited") + +def main(): + #task1 = asyncio.create_task(serverMain()) + #task2 = asyncio.create_task(clientMain()) + thread = [] + thread.append(threading.Thread(target=clientMain, args=())) + thread.append(threading.Thread(target=serverMain, args=())) + for th in thread: + th.start() + + + + #await task1 + #await task2 + +#asyncio.run(main()) +main() +print("Quited") \ No newline at end of file