微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在不同线程的不同目录中托管多个 python3 localhost 服务器

如何解决在不同线程的不同目录中托管多个 python3 localhost 服务器

我正在尝试获取一些用于在不同服务器之间进行通信的代码,以便在不同的 localhost 服务器之间进行通信,以便测试和开发不需要您事先设置服务器。

到目前为止,我已经有了使用 python 的 http.server.SimpleHTTPRequestHandlersocketserver 启动服务器的函数

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:5000GAME 服务器的页面)只会从 CLIENT 服务器的页面加载资源。 Chrome 网络标签中没有任何可疑内容

如果我交换订单(因此我在 CLIENT 线程之前启动 GAME 线程),则会发生相反的情况:导航到 localhost:4000CLIENT 服务器的页面) 只会从 GAME 服务器的页面加载资源。

所以似乎我只能访问最近创建的线程的服务器,而尝试访问旧服务器的端口只会加载最近创建的服务器的资源。

澄清一下,当我尝试访问旧服务器时没有发生重定向,它只是加载新服务器的资源,而没有任何迹象表明它不应该这样做。

访问较新服务器的资源没有问题,我可以毫无问题地做到这一点。

我试过摆弄端口号,更改位于 CLIENTGAME 目录中的资源,并浏览 Chrome 的网络选项卡,但我看不到任何可以解决此问题的方法问题,或任何错误

感谢您的帮助!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?