我正在根据条件获取某些记录并将它们存储在 msgarr 中。
我在这里使用服务器发送事件(到目前为止,我不希望有任何使用 socketio 或任何其他概念的建议)。当我打开浏览器时,来自 msgarr 的数据会被完美推送。
但是当我在另一台计算机或手机上打开另一个浏览器时,来自 msgarr 的数据会被推送到这个浏览器或另一个浏览器中。它的随机。
如何确保所有连接的浏览器都从 msgarr 获取数据?
下面是我的 python 烧瓶服务器代码:
Python 烧瓶服务器:
@app.route('/_receive')
def receive():
msgarr=[]
conn = sqlite3.connect(db_path)
sql="SELECT * FROM MESSAGES WHERE ROU='U' and NAME!='%s'" % (session.get('username'))
cursor=conn.execute(sql);
for row in cursor:
msg='<div style="float:left;padding:7px;margin:3px 0px 3px 8px;background-color:#FEFEFE;clear:both;max-width:290px;border-radius: 10px;border-bottom: 1px solid #BEBEBE;word-wrap: break-word">'+'<div style="color: #BBBBBB; font-size: small; font-family: serif;">'+row[0]+'</div>'+row[1]+'<div style="color: #BBBBBB; font-size: small; font-family: serif;">'+row[3]+'</div></div>'
msgarr.append(msg)
sql="UPDATE MESSAGES SET ROU='R' where TEXT='%s' and NAME!='%s'" % (row[1],session.get('username'))
conn.execute(sql);
conn.commit()
conn.close()
def eventStream():
str1 = ''.join(msgarr)
strlength = len(str1)
if strlength > 0:
yield "data: {}\n\n".format(str1)
return Response(eventStream(), mimetype="text/event-stream")
下面是我的客户端代码:
var source = new EventSource('/_receive');
source.onmessage=function(event) {
$("#result").append(event.data);
};