我工作的这涉及到了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的值?