[英]Displaying client side values with socketIO
我正在使用https://github.com/miguelgrinberg/Flask-SocketIO開始使用 Flask 和 SocketIO。
我想將一個字符串發布到燒瓶服務器,然后通過 SocketIO,將其發送到客戶端網頁。
我正在使用郵遞員發布令牌值。 請看截圖。
我的燒瓶服務器看起來像:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
#turn the flask app into a socketio app
socketio = SocketIO(app)
@app.route('/')
def index():
#only by sending this page first will the client be connected to the socketio instance
return render_template('index.html')
@socketio.on('connect', namespace='/ul')
def ul_connect():
# print('here is ul '+ul)
print('Client connected')
@app.route('/posting',methods=['POST'])
def posting():
token = request.form['token']
test_message(dict(data=token))
return '1'
@socketio.on('posting', namespace='/ul')
def test_message(message):
socketio.emit('response', {'data': message['data']}, broadcast=False)
@socketio.on('disconnect', namespace='/ul')
def ul_disconnect():
print('Client disconnected')
if __name__ == '__main__
我的客戶網頁包含:
$(document).ready(function(){
//connect to the socket server.
var namespace = 'http://' + document.domain + ':' + location.port + '/ul';
var socket = io.connect(namespace);
console.log('namespace ',namespace)
//var socket = io.connect('http://' + document.domain + ':' + location.port + namespace);
socket.on('connect', function() {
socket.emit('my event', {data: 'I\'m connected!'});
});
socket.on('response', function(msg) {
// do something with msg.data
console.log('response', msg.data)
});
當我發布令牌時,我在控制台中什么也看不到。 我究竟做錯了什么?
如果我理解你的例子,你正在以一種無效的方式混合 Flask/HTTP 和 Socket.IO 數據。
您的第一個問題是識別發送 POST 請求的用戶,以便您可以找到他/她的 Socket.IO 連接。 這說起來容易做起來難,HTTP 請求和 Socket.IO 連接之間沒有連接,因此您必須在雙方添加某種身份驗證,或者如果您喜歡更簡單的東西,只需記錄用戶的REMOTE_ADDR
(即並不總是可靠的)。
因此,第一步是跟蹤通過 Socket.IO 連接的用戶(為簡單起見,我將使用遠程地址):
socketio_clients = {}
@socketio.on('connect', namespace='/ul')
def ul_connect():
socketio_clients[request.remote_addr] = request.namespace
print('Client connected')
@socketio.on('disconnect', namespace='/ul')
def ul_disconnect():
del socketio_clients[request.remote_addr]
print('Client disconnected')
現在在您的POST
請求中,您可以找到用戶並發出一條消息:
@app.route('/posting',methods=['POST'])
def posting():
token = request.form['token']
client_namespace = socketio_clients.get(request.remote_addr)
if client_namespace:
client_namespace.emit('response', {'data': token}))
return '1'
abort(400) # client does not have a socket connection active
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.