I am writing a simple UDP Server that runs in a thread, based on this information
The code sending requests to the server is not shown for simplicity. Anyway, the following code does not work (requests do not seem to be received):
#!/bin/python3
import socketserver
import threading
import time
class MyServer(socketserver.DatagramRequestHandler):
def handle(self):
print("request received");
def do_nothing():
c = 0
while True:
print("up for {}s".format(c))
time.sleep(1)
c += 1
def main():
HOST, PORT = "127.0.0.1", 3600
s = socketserver.ThreadingUDPServer((HOST, PORT), MyServer)
with s:
server_thread = threading.Thread(target=s.serve_forever)
server_thread.daemon = True
server_thread.start()
do_nothing()
if __name__ == "__main__":
main()
However, if I remove the "with block":
s = socketserver.ThreadingUDPServer((HOST, PORT), MyServer)
server_thread = threading.Thread(target=s.serve_forever)
server_thread.daemon = True
server_thread.start()
now things work perfectly.
Can anyone explain why?