gpt4 book ai didi

Python SocketServer 通过线程本地存储将数据传递到主线程

转载 作者:行者123 更新时间:2023-11-30 21:50:31 25 4
gpt4 key购买 nike

抱歉,如果这个问题太基础了 - 这是我第一次尝试在 Python 中使用多线程套接字。

基本上,我正在尝试编写代码来获取 UDPServer 套接字接收的数据;套接字本身在线程内运行。 为了使主线程可以访问数据,我使用了线程本地存储(根据我读到的所有内容,这似乎是正确的方法)。下面的代码是我第一次尝试使其工作,但变量似乎没有正确更新。知道会发生什么吗?

编辑:请参阅下面的工作示例

服务器:

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

客户:

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

谢谢!!

最佳答案

成功了。是的 - 线程本地与此无关...:)

我设置了一个全局变量,并在每个修改它的函数中将其定义为全局变量(按照 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 = ""

关于Python SocketServer 通过线程本地存储将数据传递到主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14843974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com