第一次在這里發(fā)海報。我正在嘗試使用 Flask-SocketIO 組合一個聊天室應用程序,并且很難讓一個微小但至關重要的部分工作。當我在服務器中調用 emit 方法并設置 broadcast=True 標志時,預期的行為是它會在客戶端為所有用戶(包括發(fā)送者)觸發(fā)相應的 socket.on 事件。但是,我的代碼顯然只對發(fā)件人以外的所有客戶端執(zhí)行此操作。這與https://flask-socketio.readthedocs.io/en/latest/上的文檔相反,其中指出:在啟用廣播選項的情況下發(fā)送消息時,連接到命名空間的所有客戶端都會收到它,包括發(fā)送者。當不使用命名空間時,連接到全局命名空間的客戶端會收到消息。我需要它來發(fā)送消息并為發(fā)送者以及所有其他客戶端觸發(fā) socket.on 事件。誰能解釋我在這里做錯了什么?因為這似乎是一個基本功能,我一定錯過了一些非常明顯的東西。服務器代碼:import osimport requestsfrom flask import Flask, jsonify, render_template, requestfrom flask_socketio import SocketIO, emit, join_room, leave_roomapp = Flask(__name__)app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')socketio = SocketIO(app)channels = ['a', 'b', 'c', 'testing', 'abc', '123']ch_msgs = {'a': ['testing', '1234', 'high five'], 'b': ['hello']}msg_limit = 100@app.route('/')def index(): return render_template('index.html')@socketio.on('add channel')def add(data): new_channel = data channels.append(new_channel) ch_msgs[new_channel] = list() emit('announce channel', new_channel, broadcast=True)if __name__ == '__main__': app.run(debug=True, host='0.0.0.0')Javascript:document.addEventListener('DOMContentLoaded', () => { var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port); socket.on('connect', () => { document.querySelector('#add_channel').onclick = () => { const new_channel = document.querySelector('#new_channel').value; socket.emit('add channel', new_channel); }; }); socket.on('announce channel', data => { const li = document.createElement('li'); li.innerHTML = '#' + `${data}`; $('#channel_list').append(li); });});
1 回答

白豬掌柜的
TA貢獻1893條經驗 獲得超10個贊
實際上所有客戶端都在接收發(fā)送的消息,包括發(fā)送者,但這里的問題是發(fā)送者的頁面在表單提交后立即刷新,(這是表單的默認行為)從而導致所有本地數據丟失.
為了防止這種情況,您需要使用event.preventDefault()方法。在您的情況下,您可以更改事件的事件處理程序,connect如下所示:
socket.on('connect', () => {
document.querySelector('#add_channel').onclick = event => {
event.preventDefault();
const textinput = document.querySelector('#new_channel')
const new_channel = textinput.value;
textinput.value = ""; // Clear input after value is saved
socket.emit('add channel', new_channel);
};
});
添加回答
舉報
0/150
提交
取消