每秒钟更新一次的Bottle Websocket示例

时间:2019-02-26 00:25:34

标签: python jquery websocket bottle gevent

当我试图以最少的JavaScript知识来了解websocket时,我的理解陷入了重大空白。一个干净的例子似乎是 Bottle websockets example

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

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

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

但是我无法做出让Jquery“模式”适应Bottle的飞跃。如果有人有时间来摘录,那么它就会变得很明显。谢谢。

1 个答案:

答案 0 :(得分:0)

人们倾向于使网络套接字过于复杂。我喜欢Gevent,因为它非常容易实现。但是,有一些警告。如果将websocket与当前的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>