【问题标题】:How do I serve a Websocket Application written in Python using Twisted Framework如何使用 Twisted Framework 提供用 Python 编写的 Websocket 应用程序
【发布时间】:2021-03-14 12:15:51
【问题描述】:

我使用 Twisted 框架编写了一个 websocket 服务器应用程序。我是新手,正在尝试弄清楚如何将其作为应用程序提供服务,以便我可以使用 NGINX 反向代理它。

应用程序主体如下:

if __name__ == "__main__":
    #Clear redis cache
    R.flushdb()
    log.startLogging(sys.stdout)
    contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                          'keys/server.crt')
    ServerFactory = BroadcastServerFactory
    factory = BroadcastServerFactory("wss://127.0.0.1:8080")
    factory.protocol = BroadcastServerProtocol
    resource = WebSocketResource(factory)
    root = File(".")
    root.putChild(b"ws", resource)
    site = Site(root)
    reactor.listenSSL(8080, site, contextFactory)
    reactor.run()

我的理解是我需要创建一个 WSGI 应用程序,但我对如何执行此操作感到困惑。我不确定如何将此程序更改为 WSGI。当我使用 Django 和 Flash 时,它们有一个 WSGI 文件,但这个新项目只是一个使用 Twisted 框架的 python 文件。

抱歉,我有点难以解释。

【问题讨论】:

  • nginx 不要求您将服务器实现为 WSGI 应用程序。 nginx 不关心你如何实现你的 HTTP 端点。您的服务器已经在监听 any:8080。设置你的 nginx 反向代理指向那里,你就完成了。
  • 谢谢,我需要使用 twistd 来运行应用程序,然后配置一个我指向 NGINX 的 unix 套接字吗?

标签: python-3.x twisted wsgi autobahn


【解决方案1】:

我所做的是更改代码,使其不再有 if 语句,如下所示:

#New imports
from twisted.application import internet,service

#Bottom of file
R.flushdb()
log.startLogging(sys.stdout)
contextFactory = ssl.DefaultOpenSSLContextFactory('keys/server.key',
                                                        'keys/server.crt')
ServerFactory = BroadcastServerFactory
factory = BroadcastServerFactory("wss://127.0.0.1:8080")
factory.protocol = BroadcastServerProtocol
resource = WebSocketResource(factory)
application = service.Application("picserver")
service = internet.TCPServer('8080', factory) 
resource = WSGIResource(reactor, reactor.getThreadPool(), factory)
root = File(".")
root.putChild(b"ws", resource)
site = Site(root)
reactor.listenSSL(8080, site, contextFactory)
service.setServiceParent(application)
reactor.run()

我将文件重命名为“server.tap”,但我认为这没有必要。然后代码更改允许我使用以下命令将程序作为守护程序运行:

twistd -y server.py 

然后我在 /etc/systemd/system 中创建了一个 .service 文件,如下所示:

[Unit]
Description=picserver startup script 
After=network.target

[Service]
User=django
Group=www-data
Environment="DBNAME=mydb"
Environment="DBUSER=dbuser"
Environment="DBPASSWORD=password"
ExecStart=/home/<username>/Documents/python/environments/gameservertest/bin/python /home/<username>/Documents/python/environments/gameservertest/bin/twistd -y /home/<username>/Documents/python/picturegameserver/server.tap
WorkingDirectory=/home/<username>/Documents/python/picturegameserver/
Restart=always

[Install]
WantedBy=multi-user.target

我现在可以使用“systemctl”将其作为服务运行,并且可以连接在服务器上本地运行的前端。目前,我认为我不需要配置 Nginx 来反向代理它,因为我可以让前端在同一台服务器上运行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    • 2018-10-30
    • 2011-12-08
    相关资源
    最近更新 更多