【问题标题】:socket server and webserver running in Python在 Python 中运行的套接字服务器和网络服务器
【发布时间】:2020-12-09 15:48:54
【问题描述】:

我正在尝试在 Python 中运行 WebServer 和套接字服务器。我有每个单独工作的代码,但我不能让他们一起去,他们每个人都从一个阻塞呼叫开始 - 有人可以指出我的新手吗?以下错误?

start_server = websockets.serve(hello, "", 8765)
print("one")
import WWW_Server
  #The imported file has the following lines:
    ##from waitress import serve
    ##
    ##def srvThread(SrvPort=5000):
    ##    flaskThread()
    ##    serve(app, host='0.0.0.0', port=SrvPort)
    ##
    ##threading.Thread(target = srvThread(2000)).start()
    ##print("hello")  <<<< Why don't I see this printed out?
print("two") # <<<< Why don't I see this printed out?
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
print("three")

【问题讨论】:

标签: python web


【解决方案1】:

您没有看到“hello”或“two”打印出来,因为您没有通过导入中的threading.Thread(target = srvThread(2000)).start() 行。这会启动一个阻塞线程(这就是.start() 所做的),它只是挂在那里,永远不会回到你的主线程。

为此,我建议使用python's multiprocessing library,它允许真正的并行性。

此外,您的代码编写方式会让您感到沮丧和焦虑 - 一般来说,您从不希望您的导入独立于您的 main.它会导致混乱和意大利面条代码,以及非常令人沮丧的调试堆栈。理想情况下,您的导入就像库。他们设置了代码供您从主服务器调用。

【讨论】:

  • 谢谢 - 这正是我需要的指针。是的..我的导入现在只是一个 hack,不是正确的方法!
猜你喜欢
  • 1970-01-01
  • 2017-08-05
  • 2011-04-21
  • 1970-01-01
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-22
相关资源
最近更新 更多