Question

Sorry if this question is too basic - this is the first time that I try using multithreaded sockets in Python.

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. 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). 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?

EDIT: see below for a working example

Server:

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 = ""

Client:

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

Thanks!!

Was it helpful?

Solution

Made it work. And yes - Thread local has nothing to do with this... :)

I have set a global variable and defined it as global in each function modifying it (as per this very helpful answer)

import socket
import threading
import SocketServer

data = ""

class UDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        global data
        data = self.request[0].strip()

class ThreadedUDPServer(SocketServer.ThreadingMixIn, SocketServer.UDPServer):
    pass

if __name__ == "__main__":

    ReceiverSocket = ThreadedUDPServer(("localhost",11111), UDPHandler)
    ServerThread = threading.Thread(target=ReceiverSocket.serve_forever)
    ServerThread.start()

    while 1:
        if data:
            print data
            data = ""

OTHER TIPS

Try using a global variable BUT make sure that you define it as global in EVERY thread and function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top