Note that there are some explanatory texts on larger screens.

plurals
  1. POPython SocketServer passing data to the main thread via Thread local storage
    text
    copied!<p>Sorry if this question is too basic - this is the first time that I try using multithreaded sockets in Python.</p> <p>Basically, I'm trying to write code that gets data that's being received by a UDPServer socket; the socket itself is running inside of a thread. <del>In order to make the data accessible to the main thread, I'm using Thread local storage (it seems that's the correct way to do it based on everything that I read)</del>. The code below is my first attempt to make it work, but the variable doesn't seem to be properly updated. Any idea about what could be happening?</p> <p>EDIT: see below for a working example</p> <p>Server:</p> <pre><code>import socket import threading import SocketServer data = threading.local() class UDPHandler(SocketServer.BaseRequestHandler): def handle(self): data.outputString = self.request[0].strip() class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer): def __init__(self, serverAddress, handlerClass): SocketServer.UDPServer.__init__(self, serverAddress, handlerClass) data.outputString = "" if __name__ == "__main__": ReceiverSocket = ThreadedUDPServer(("localhost",11111), UDPHandler) ServerThread = threading.Thread(target=ReceiverSocket.serve_forever) ServerThread.daemon = True ServerThread.start() while 1: if data.outputString: print data.outputString data.outputString = "" </code></pre> <p>Client:</p> <pre><code>import socket import sys HOST, PORT = "localhost", 11111 data = " ".join(sys.argv[1:]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(data + "\n", (HOST, PORT)) </code></pre> <p>Thanks!!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload