首页 > 解决方案 > 错误 socketio 库:“socketio.exceptions.ConnectionError:连接被服务器拒绝”

问题描述

如果我可以连接到套接字,我正在尝试从服务器外部的任何地方连接到我在 NodeJS 中配置的套接字,但是当尝试从同一服务器连接时,它显示消息:“socketio.exceptions.ConnectionError: Connection被服务器拒绝”

我配置的端口是 8085 我尝试添加: - http://localhost : 8085 - https://localhost : 8085 - http://127.0.0.1 : 8085 - https://127.0.0.1 : 8085 - *:8085 - 192.168.4.7:8085 - 公共IP:8085

import socketio
sio = socketio.Client()
sio.connect('https://localhost:8085')

当我从服务器外部连接时,它允许我与套接字交互。问题是本地服务器,因为它立即向我显示消息“连接被拒绝”

标签: pythonsocket.io

解决方案


我也有同样的问题。

但是当查看 scoketio 的文档时,它表明有两个或多个实例正在运行。一个用于server side,其他在 上client side

让服务器文件运行服务器并使用客户端文件连接到服务器。下面给出一个例子。

server.py

# using eventlet, visit the docs for more info
import eventlet
import socketio

sio = socketio.Server()
app = socketio.WSGIApp(sio, static_files={
    '/': {'content_type': 'text/html', 'filename': 'index.html'}
})

@sio.event
def connect(sid, environ):
    print('connect ', sid)

@sio.event
def my_message(sid, data):
    print('message ', data)

@sio.event
def disconnect(sid):
    print('disconnect ', sid)

if __name__ == '__main__':
    # change the 5000 to any port you want
    # leave the 'localhost' empty string to run on your IP
    eventlet.wsgi.server(eventlet.listen(('localhost', 5000)), app)

client.py

import socketio

sio = socketio.Client()

@sio.event
def connect():
    print('connection established')

@sio.event
def my_message(data):
    print('message received with ', data)
    sio.emit('my response', {'response': 'my response'})

@sio.event
def disconnect():
    print('disconnected from server')

sio.connect('http://localhost:5000/')
sio.wait()

然后,运行第server.py一个:

C:\User\new>py server.py
(12080) wsgi starting up on http://127.0.0.1:5000

然后运行client.py

C:\User\new>py clinet.py
connection established

并且您的套接字文件正在运行。

如果你已经体验过这个过程,你 觉得很容易。因为这是开始和学习的完美和最简单的方式socket.iojavascriptsocket.io


推荐阅读