如何解决在不同线程的不同目录中托管多个 python3 localhost 服务器
我正在尝试获取一些用于在不同服务器之间进行通信的代码,以便在不同的 localhost
服务器之间进行通信,以便测试和开发不需要您事先设置服务器。
到目前为止,我已经有了使用 python 的 http.server.SimpleHTTPRequestHandler
和 socketserver
启动服务器的函数:
113 def start_server(directory='',PORT=8000):
1 old_dir = os.path.dirname(__file__)
2 if not directory:
3 directory = os.path.dirname(__file__)
4
5 os.chdir(directory)
6 Handler = http.server.SimpleHTTPRequestHandler
7 with socketserver.Tcpserver(("",PORT),Handler) as httpd:
8 print("Serving at port {},on directory {}".format(PORT,directory))
9 try:
10 httpd.serve_forever()
11 except KeyboardInterrupt:
12 pass
13 httpd.server_close()
14 os.chdir(old_dir)
该函数被调用两次,每个线程一次,在这些行上使用 python 的 threading
模块:
(genghis_client_dir
只是本地目录的绝对路径)
80 GAME_PORT = 5000
1 thread_game = threading.Thread(
target=start_server,kwargs={'directory':os.path.dirname(os.path.abspath(__file__)),'PORT': GAME_PORT}
)
2 thread_game.start()
3
4 CLIENT_PORT = 4000
5 thread_client = threading.Thread(
target=start_server,kwargs={'directory':genghis_client_dir,'PORT':CLIENT_PORT}
)
6 thread_client.start()
现在的问题是我似乎无法让 GAME
本地服务器和 CLIENT
本地服务器分别运行。
如果我按照上面的方式运行代码,那么导航到 localhost:5000
(GAME
服务器的页面)只会从 CLIENT
服务器的页面加载资源。 Chrome 网络标签中没有任何可疑内容。
如果我交换订单(因此我在 CLIENT
线程之前启动 GAME
线程),则会发生相反的情况:导航到 localhost:4000
(CLIENT
服务器的页面) 只会从 GAME
服务器的页面加载资源。
所以似乎我只能访问最近创建的线程的服务器,而尝试访问旧服务器的端口只会加载最近创建的服务器的资源。
澄清一下,当我尝试访问旧服务器时没有发生重定向,它只是加载新服务器的资源,而没有任何迹象表明它不应该这样做。
访问较新服务器的资源没有问题,我可以毫无问题地做到这一点。
我试过摆弄端口号,更改位于 CLIENT
和 GAME
目录中的资源,并浏览 Chrome 的网络选项卡,但我看不到任何可以解决此问题的方法问题,或任何错误。
感谢您的帮助!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。