[英]Notification ping from backend using Web sockets and tornado
我是網絡套接字的新手。 我在后端使用Tornado / python,並編寫了以下代碼。
class BaseWebSocketHandler(websocket.WebSocketHandler):
"""Base Class to establish an websocket connection."""
def open(self):
"""Opening the web socket connection."""
self.write_message('Connection Established.')
def on_message(self, message):
"""On message module send the response."""
pass
def on_close(self):
"""Close the connection."""
self.write_message('bye')
class MeterInfo(BaseWebSocketHandler):
"""Establish an websocket connection and send meter readings."""
def on_message(self, message):
"""On message module send to the response."""
self.write_message({'A': get_meter_reading()})
我的JavaScript代碼如下所示,
var meter = new WebSocket("ws://"+window.location.host+"/socket/meterstatus/");
meter.onopen = function() {
$('#meter-well').text('Establishing connection...');
};
meter.onmessage = function (evt) {
var data = JSON.parse(evt.data)
var text = "<div class='meter'><h2>" + data.A +"</h2></div>";
$('#meter-pre').html(text);
};
meter.onclose = function (evt) {
console.log(JSON.parse(evt.data))
$('#meter-pre').append('\n'+evt.data);
};
window.setInterval(function(){ meter.send('') }, 100);
我每100毫秒向后端發出一個空白的網絡套接字請求請求。 這對我來說似乎是一個非常糟糕的解決方案。 有沒有更好的方法來執行此操作,而無需在后端進行多次send()操作,而僅在抄表讀數上僅通知用戶?
我也已經通過MQTT協議以更好的方式做到這一點,有人可以建議我如何實現它嗎?
您幾乎在這里找到了解決問題的方法:
class MeterInfo(BaseWebSocketHandler):
"""Establish an websocket connection and send meter readings."""
def on_message(self, message):
"""On message module send to the response."""
self.write_message({'A': get_meter_reading()})
如您write_message
龍卷風需要一些事件通過write_message
方法來ping客戶端。 您正在使用來自客戶端的新消息作為此類事件,請嘗試將其更改為簡單的超時調用作為事件,如下所示:
# BaseWebSocketHandler removed, because we need to track all opened
# sockets in the class. You could change this later.
class MeterInfo(websocket.WebSocketHandler):
"""Establish an websocket connection and send meter readings."""
opened_sockets = []
previous_meter_reading = 0
def open(self):
"""Opening the web socket connection."""
self.write_message('Connection Established.')
MeterInfo.opened_sockets.append(self)
def on_close(self):
"""Close the connection."""
self.write_message('bye')
MeterInfo.opened_sockets.remove(self)
@classmethod
def try_send_new_reading(cls):
"""Send new reading to all connected clients"""
new_reading = get_meter_reading()
if new_reading == cls.previous_meter_reading:
return
cls.previous_meter_reading = new_reading
for socket in cls.opened_sockets:
socket.write_message({'A': new_reading})
if __name__ == '__main__':
# add this after all set up and before starting ioloop
METER_CHECK_INTERVAL = 100 # ms
ioloop.PeriodicCallback(MeterInfo.try_send_new_reading,
METER_CHECK_INTERVAL).start()
# start loop
ioloop.IOLoop.instance().start()
請查看tornado.ioloop文檔以獲取有關PeriodicCallback和其他選項的更多信息。
如果要將龍卷風用於MQTT協議,則無法使用龍卷風。 例如,您可以嘗試使用emqtt服務器 ,但這是實際的服務器,而不是編寫應用程序的框架,因此恕我直言,使用龍卷風通過Web套接字ping會更全面。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.