当我试图理解具有最少javascript知识的websockets时,我遇到了我理解中的主要漏洞。一个干净的例子看起来像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“模式”适应瓶子。如果有人有时间只是一个片段,也许会变得很明显。谢谢。
人们倾向于过度复杂的websockets。我喜欢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>