[英]Flask socketio not receiving any message from javascript even after the connection is established
在燒瓶和javascript之間建立連接后,我試圖從javascript獲取響應。onconnect()函數正常工作,但onmessage()無法工作。
我也嘗試在javascript中將廣播與emit方法一起使用,但是它不起作用。
這是我的app.py
app=Flask(__name__)
bootstrap=Bootstrap(app)
socketio=SocketIO(app)
app.config['SECRET_KEY']="MY_KEY"
@app.route('/')
def login():
return render_template('index.html')
@app.route('/home',methods=['GET','POST'])
def home():
if(request.method=='POST'):
data=request.form
name=data['name']
return render_template('message.html',name=name)
else:
return render_template('index.html')
@socketio.on('connect')
def onconnect():
print("connect")
@socketio.on('message')
def onmessage(message):
print('message')
if(__name__=='__main__'):
socketio.run(app)
這是我的javascript文件
const ws =io.connect(window.location.href)
ws.on('connect', function() {
console.log("Connection estalished")
ws.emit("adsd",broadcast=true)
});
編輯:javscript中有一個錯誤。
const ws =io()
這應該用於建立連接,而不是先前的方法。
我的項目完成。 github項目的鏈接
首先,只有服務器可以廣播,客戶端只能向服務器發射。
其次,您將發出一個名為adsd
的事件,因此您需要在服務器中添加該事件的處理程序。 例如:
@socketio.on('adsd')
def adsd_handler():
print('got adsd!')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.