瓶子+网络插座



是否可以在同一应用程序(同一端口)中托管普通的Bottle应用程序和WebSocket应用程序(例如:https://github.com/defnull/bottle/blob/master/docs/async.rst)?因此,/ws 将转到 WebSocket 处理程序,而所有其他处理程序将正常路由到其他瓶子处理程序。

确实如此。

服务器:

#!/usr/bin/python
import json
from bottle import route, run, request, abort, Bottle ,static_file
from pymongo import Connection
from gevent import monkey; monkey.patch_all()
from time import sleep
app = Bottle()
@app.route('/websocket')
def handle_websocket():
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')
    while True:
        try:
            message = wsock.receive()
            wsock.send("Your message was: %r" % message)
            sleep(3)
            wsock.send("Your message was: %r" % message)
        except WebSocketError:
            break
@app.route('/<filename:path>')
def send_html(filename):
    return static_file(filename, root='./static', mimetype='text/html')

from gevent.pywsgi import WSGIServer
from geventwebsocket import WebSocketHandler, WebSocketError
host = "127.0.0.1"
port = 8080
server = WSGIServer((host, port), app,
                    handler_class=WebSocketHandler)
print "access @ http://%s:%s/websocket.html" % (host,port)
server.serve_forever()

包含 javascript 的 html 页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <script type="text/javascript">
    var ws = new WebSocket("ws://localhost:8080/websocket");
    ws.onopen = function() {
        ws.send("Hello, world");
    };
    ws.onmessage = function (evt) {
        alert(evt.data);
    };
  </script>
</head>
<body>
</body>
</html>

客户:

#!/usr/bin/python
from websocket import create_connection
ws = create_connection("ws://localhost:8080/websocket")
print "Sending 'Hello, World'..."
ws.send("Hello, World")
print "Sent"
print "Reeiving..."
result =  ws.recv()
print "Received '%s'" % result
ws.close()

这很可能不是最简单的答案,但我刚刚完成了一个使用 Nginx 和 uWSGI over Pyramid 的测试环境,一旦你设置好了它,你就可以非常非常轻松地扩展它,例如,如果你的/ws 拉动了太多资源,使用 Nginx+uWSGI 将/ws 重新定位到不同的硬件是微不足道的。我的背景是金字塔,我的uWSGI经验只在测试方面,但在我的阅读中,它似乎是一个应该运作良好的解决方案。瓶子说明是快速谷歌搜索的结果。

概念:

这个概念是在 app.serve_forever() 调用之前获取您的应用程序,即您的应用程序 = make_wsgi_app.from_config(config),而是使用 uwsgi 将您的应用程序"服务"到套接字 app1.sock。有很多方法可以配置 uWSGI。uWSGI站点提供了更多配置uWSGI以与您的应用程序通信的方法的文档。Nginx带有至少在当前版本中本地使用uWSGI套接字的配置。您只需将 uwsgi_pass unix:///tmp/app1.sock; 路径与参数一起传递给站点配置。在同一个站点 conf 文件中执行此操作两次,一次用于位置/{,一次用于位置/ws { 指向它们各自的应用程序袜子文件,您应该很高兴。

在设置测试环境时,将应用程序作为文件提供给套接字的概念对我来说是新的,我希望这有所帮助。

获得什么:

恩金克斯
uWSGI

操作方法:

从本教程中提取 nginx 和 uwsgi 设置信息,并将其迎合到您的应用程序,在此处进行瓶子特定的设置,或前往 uwsgi 站点并查看其配置说明。每个特定技术的文档都非常好,因此即使缺乏组合示例,让它们协同工作也不难。对于Nginx和uWSGI,有大量的配置设置,所以一定要看看这些设置。

最新更新