面试题答案
一键面试from flask import Flask
from flask_socketio import SocketIO, send, emit
app = Flask(__name__)
app.config['SECRET_KEY'] ='secret!'
socketio = SocketIO(app)
# 处理连接事件
@socketio.on('connect')
def handle_connect():
print('Client connected')
# 处理断开连接事件
@socketio.on('disconnect')
def handle_disconnect():
print('Client disconnected')
# 处理自定义事件
@socketio.on('custom_event')
def handle_custom_event(data):
print('Received custom event with data:', data)
emit('custom_response', {'response': 'Server received your custom event'})
if __name__ == '__main__':
socketio.run(app, debug=True)
在上述代码中:
@socketio.on('connect')
装饰器用于定义处理连接事件的函数handle_connect
,当客户端连接到服务器时会触发此函数。@socketio.on('disconnect')
装饰器用于定义处理断开连接事件的函数handle_disconnect
,当客户端与服务器断开连接时会触发此函数。@socketio.on('custom_event')
装饰器用于定义处理自定义事件custom_event
的函数handle_custom_event
,当服务器接收到名为custom_event
的事件时会触发此函数,并可以通过data
参数获取客户端发送的数据。同时,函数内使用emit
向客户端发送名为custom_response
的响应事件。