我正在从事一个涉及通过 TCP 发送数据的项目。使用 ThreadedTCPServer 我已经能够做到这一点。服务器线程只需要读取传入的数据字符串并设置变量的值。同时我需要主线程来查看这些变量的值变化。到目前为止,这是我的代码,只是从 ThreadedTCPServer 示例中修改的:
import socket
import threading
import SocketServer
x =0
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
# a few lines of code in order to decipher the string of data incoming
x = 0, 1, 2, etc.. #depending on the data string it just received
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
pass
if __name__ == "__main__":
# Port 0 means to select an arbitrary unused port
HOST, PORT = 192.168.1.50, 5000
server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
# Start a thread with the server -- that thread will then start one
# more thread for each request
server_thread = threading.Thread(target=server.serve_forever)
# Exit the server thread when the main thread terminates
server_thread.daemon = True
server_thread.start()
print "Server loop running in thread:", server_thread.name
while True:
print x
time.sleep(1)
server.shutdown()
所以这应该工作的方式是程序不断地打印 x 的值,并且随着新消息的进入 x 的值应该改变。似乎问题在于它在主线程中打印的 x 与在服务器线程中被分配新值的 x 不同。如何从我的服务器线程更改主线程中 x 的值?