You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

服务器端能否使用两个独立的事件处理函数?Socket.IO实现咨询

解决方案:拆分服务器端函数

完全可以将服务器端的逻辑拆分为两个独立函数,一个负责打印客户端发来的消息,另一个负责向客户端发送响应。以下是具体实现:

修改后的服务器端代码(server_sends_client_receives.py)

from flask import Flask, render_template
from flask_socketio import SocketIO, emit, disconnect
from time import sleep

async_mode = None

app = Flask(__name__)

socketio_obj = SocketIO(app, async_mode=async_mode)


@app.route('/')
def index():
    return render_template('server_sends_client_receives.html',
                           sync_mode=socketio_obj.async_mode)

# 负责打印客户端消息的函数
def print_client_message(arg1):
    print('received from the client : ', arg1['hello'])
    print('received from the client : ', arg1['world'])

# 负责向客户端发送响应的函数
def send_server_response():
    emit('server_to_client', {'data': 'received from the server'})
    disconnect()

@socketio_obj.on('client_to_server', namespace='/test')
def handle_client_event(arg1):
    try:
        print_client_message(arg1)  # 调用打印函数
        send_server_response()      # 调用发送响应函数
    except Exception as ex:
        print(ex)


if __name__ == '__main__':
    socketio_obj.run(app, host='0.0.0.0', port=80, debug=True)

代码说明

  • 原函数中的打印逻辑被抽离为print_client_message函数,专门处理客户端消息的控制台输出。
  • 发送响应和断开连接的逻辑被抽离为send_server_response函数,专注于向客户端返回消息并结束连接。
  • 保留client_to_server事件的主处理函数handle_client_event作为入口,调用拆分后的两个函数实现逻辑解耦。

客户端代码无需修改

原客户端代码(server_sends_client_receives.html)保持不变即可,客户端的事件触发和响应逻辑未发生变化,仅服务器端内部做了职责拆分。

内容的提问来源于stack exchange,提问作者user366312

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 12:30:42