【问题标题】:Bottle Websockets Example That Updates Every Few Seconds每隔几秒更新一次的 Bottle Websockets 示例
【发布时间】:2019-07-19 11:32:00
【问题描述】:

当我试图用最少的 javascript 知识来理解 websockets 时,我在理解上遇到了重大漏洞。一个干净的例子似乎 Bottle websockets example

那里的 websockets 服务器和客户端示例对我有用。但我想例如在 HTML 客户端上每 10 秒更新一次时间。所以我只是在服务器上做了。

while True:
    wsock.send("Time: " + str(datetime.datetime.now()))
    time.sleep(10)

时间显示一次但从不更新。尝试为 Raspberry Pi 项目执行此操作时,我遇到了一个更新传感器值的 nodejs 示例;在这个例子中,有一些 Jquery 代码我认为我可以适应瓶子示例中的 HTML 文件代码......他们正在使用 Jquery .data 来“挂钩”一个可能会更新的表格元素。 NodeJS Updating weosockets example

但我无法将 Jquery“模式”适应 Bottle。如果有人有时间只是一个sn-p也许它会变得很明显。谢谢。

【问题讨论】:

  • 我们需要更多代码来帮助我怀疑。我在我的应用程序中使用 websockets,它相对简单。如果您提供代码,我可以提供更多帮助。

标签: python jquery websocket bottle gevent


【解决方案1】:

人们倾向于使 websocket 过于复杂。我喜欢 Gevent,因为它非常容易实现。然而,有一些警告。如果将 websockets 与当前的 WSGI 应用程序结合使用,则在等待接收时会阻塞单个连接,因此请添加超时。

这是一个在 Gevent Websockets 下运行的示例。这使它成为 ASYNC 并允许双向通信。

import gevent
from gevent import monkey, signal, Timeout, sleep, spawn as gspawn
monkey.patch_all()
from gevent.pywsgi import WSGIServer
from geventwebsocket.handler import WebSocketHandler
from geventwebsocket import WebSocketError
import bottle
from bottle import get, route, template, request, response, abort, static_file
import ujson as json

@route('/static/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='static')

@route('/ws/remote')
def handle_websocket():
    message = 'TEST'
    wsock = request.environ.get('wsgi.websocket')
    if not wsock:
        abort(400, 'Expected WebSocket request.')
    while 1:
        wsock.send(message) # example of how to send data
        sleep(10) #pause this thread only for 10 seconds
        try:
            with Timeout(2, False) as timeout: #if you want to receive
                message = wsock.receive()
            if message:
                message = json.loads(message)
                if 'command' in message:
                    r.command(message['command'])
        except WebSocketError:
            break
        except Exception as exc:
            print(str(exc))


@get('/')
def remote():
    return template('templates/remote.tpl', title='WebsocketTest', websocket=WEBSOCKET, command='command', status=status)


if __name__ == '__main__':
    r=None
    status="Connecting..."
    gspawn(initialize)
    print 'Started...'
    HOST = socket.gethostbyname(socket.gethostname())
    HOST = 'localhost'
    WEBSOCKET =  'ws://{}/ws/remote'.format(HOST)
    botapp = bottle.app()
    server = WSGIServer(("0.0.0.0", 80), botapp, handler_class=WebSocketHandler)
    def shutdown():
        print('Shutting down ...')
        server.stop(timeout=60)
        exit(signal.SIGTERM)
    gevent.signal(signal.SIGTERM, shutdown)
    gevent.signal(signal.SIGINT, shutdown) #CTRL C
    server.serve_forever()

那么在你的 HTML 中你真的应该使用重新连接 websocket 库 https://github.com/joewalnes/reconnecting-websocket

<button id="TRIGGERED" type="button" class="btn btn-outline-primary">TRIGGER</button>
<script type="text/javascript" src="/static/reconnecting-websocket.min.js"></script>
<script>
var ws = new ReconnectingWebSocket('{{websocket}}');
ws.reconnectInterval = 3000;
ws.maxReconnectAttempts = 10;

ws.onmessage = function (evt) {
    var wsmsg = JSON.parse(evt.data);
    console.log(evt.data)
    };


$("button").click(function() {
    <!--console.log(this.id);-->
    ws.send(JSON.stringify({'{{command}}': this.id}));
});
</script>

【讨论】:

    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 2011-12-07
    • 2011-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多