1
到目前爲止,我有基本代碼將我的websocket服務器連接到websocket客戶端。我使用Autobahn作爲服務器代碼,而高級REST客戶端作爲客戶端。在DBAlertProtocol
類中的一個單獨的方法中,我長時間輪詢CouchDB中的數據庫以瞭解發生的任何更改,即添加,刪除,更新等。此方法在websocket連接打開5秒後獲取調用。使用sendMessage進行CouchDB更改使用Autobahn WebSocket庫
使用sendMessage
時出現問題,其中數據未顯示在客戶端,或者有時需要很長時間才能到達。
有沒有辦法改變通訊選項?數據可能太大而無法發送?我想弄清楚爲什麼我的其他示例可以成功發送數據,但couchdb更改通知不能。
下面是我到目前爲止的代碼。
在此先感謝!
server.py
import sys
import logging
import couchdb
from twisted.python import log
from twisted.internet import reactor
from autobahn.twisted.websocket import WebSocketServerFactory, \
WebSocketServerProtocol, listenWS
from autobahn.twisted.resource import WebSocketResource
couch = couchdb.Server("http://localhost:5984/")
db = couch['event_db']
class DBAlertProtocol(WebSocketServerProtocol):
def onConnect(self, request):
print("Connection made on server side")
def onOpen(self):
print("WebSocket connection open.")
reactor.callLater(5, self.check_db_changes)
def check_db_changes(self):
since = 1
print("\nstart loop\n")
while True:
changes = db.changes(since=since, include_docs=True)
since = changes['last_seq']
no_docs_changed = len(changes)
counter = 0
for changeset in changes['results']:
print("\nChange detected!\n")
try:
doc = db[changeset['id']]
except couchdb.http.ResourceNotFound:
print("Resource not found, or was deleted.")
else:
counter += 1
print("Number of docs effected: {}".format(str(counter)))
# Send change data to MW
self.sendMessage(str(changeset))
def onClose(self, wasClean, code, reason):
print("WebSocket closed on server side: {}".format(reason))
def onMessage(self, payload, isBinary):
print("Data received from database: {}".format(payload))
self.sendMessage("Message received.")
class DBAlertFactory(WebSocketServerFactory):
protocol = DBAlertProtocol
def main():
log.startLogging(sys.stdout)
port = 8000
factory = DBAlertFactory(u"ws://127.0.0.1:8000")
listenWS(factory)
print("Listening on port: {}".format(str(port)))
print("Starting reactor...")
reactor.run()
if __name__ == "__main__":
main()
這實際上是我使用而現在完美的作品!謝謝。 – Brian