Python SocketIO连接被服务器拒绝,Django WSGI配置求助
Django项目WSGI文件使用SocketIO客户端报错问题
问题背景
不确定是否应该在Django项目的wsgi.py文件中使用SocketIO客户端,启动服务器时出现连接被拒绝的报错,想确认是否遗漏配置步骤。
我的wsgi.py文件内容
import os import sys from django.core.wsgi import get_wsgi_application import socketio sio = socketio.Client() print('Created socketio client') @sio.event def connect(): print('connected to server') @sio.event def disconnect(): print('disconnected from server') sio.connect('http://localhost:8000/socket.io/') sio.wait() app_path = os.path.abspath(os.path.join( os.path.dirname(os.path.abspath(__file__)), os.pardir)) sys.path.append(os.path.join(app_path, 'myapp')) if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': from raven.contrib.django.raven_compat.middleware.wsgi import Sentry os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production") application = get_wsgi_application() if os.environ.get('DJANGO_SETTINGS_MODULE') == 'config.settings.production': application = application
初始报错信息
File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\socketio\client.py", line 246, in connect six.raise_from(exceptions.ConnectionError(exc.args[0]), None) File "<string>", line 3, in raise_from socketio.exceptions.ConnectionError: Connection refused by the server
更新1:完整报错堆栈
Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x000001E926004C18> Traceback (most recent call last): File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 140, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\commands\runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 44, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\Programming\python\myapp\config\wsgi.py", line 34, in <module> sio.connect('http://localhost:8000/socket.io/') File "C:\Users\prabh\AppData\Local\Programs\Python\Python37\lib\site-packages\socketio\client.py", line 246, in connect six.raise_from(exceptions.ConnectionError(exc.args[0]), None) File "<string>", line 3, in raise_from
更新2:前端SocketIO代码
socket.on('connect', function() { console.log('CONNECTED'); socket.emit('on message', 'data'); });
问题分析与解决
核心问题:wsgi.py中不能直接启动SocketIO客户端
wsgi.py是Django的WSGI入口文件,服务器启动时会优先加载该文件。你在文件顶部直接调用sio.connect()和sio.wait(),此时Django服务器还未完成初始化,localhost:8000的服务根本没有启动,自然会触发连接拒绝错误。另外,sio.wait()会阻塞线程,导致Django服务器永远无法完成启动流程。
正确处理方式
- 移除wsgi.py中的SocketIO客户端代码:该文件仅负责初始化Django的WSGI应用,不适合放置客户端连接逻辑。
- SocketIO客户端的正确位置:
- 若后端需主动连接外部SocketIO服务,应在Django的
views.py、自定义管理命令或信号中执行连接操作,确保服务器完全启动后再触发连接。 - 若为前后端SocketIO通信,后端需配置SocketIO服务器(比如结合
python-socketio与ASGI模式),而非在后端启动客户端连接自身。
- 若后端需主动连接外部SocketIO服务,应在Django的
前后端SocketIO通信的配置提示
如果需求是前端与Django后端做SocketIO交互,需要:
- 切换到ASGI模式运行Django(Django 3.0+支持),搭配
python-socketio搭建兼容ASGI的SocketIO服务器。 - 后端定义SocketIO事件处理函数,前端通过对应地址连接后端的SocketIO服务即可。
临时测试方案
如果只是想测试SocketIO客户端连接,可以编写独立Python脚本,在Django服务器启动后单独运行:
import socketio sio = socketio.Client() print('Created socketio client') @sio.event def connect(): print('connected to server') @sio.event def disconnect(): print('disconnected from server') sio.connect('http://localhost:8000/socket.io/') sio.wait()
内容的提问来源于stack exchange,提问作者Prabhakaran
相关产品推荐
相关产品推荐

