我正在使用https://github.com/miguelgrinberg/Flask-SocketIO开始使用flask和SocketIO。
我想将一个字符串发布到烧瓶服务器,然后通过SocketIO将其发送到客户端网页。
我正在使用邮递员发布令牌值。请看截图。
我的烧瓶服务器如下:
eventListener
我的客户网页包含:
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__
当我发布令牌时,我在控制台中看不到任何内容。我做错了什么?
答案 0 :(得分:2)
如果我理解你的例子,你将以无效的方式混合Flask / HTTP和Socket.IO数据。
您的第一个问题是识别发送POST请求的用户,以便您可以找到他/她的Socket.IO连接。这说起来容易做起来难,HTTP请求和Socket.IO连接之间没有连接,所以你必须在双方都添加某种身份验证,或者如果你更喜欢更简单的东西,只需记录用户的{{1 (这并不总是可靠的)。
所以第一步是跟踪通过Socket.IO连接的用户(为简单起见,我将使用远程地址):
REMOTE_ADDR
现在,在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