Flask-SocketIO:无法连接到命名空间

Flask-SocketIO: Cannot connect to a namespace

我在使用 Flask-SocketIO 时通过 Websockets 连接到我的服务器时遇到问题。如果我不指定自定义名称空间,一切正常,但如果我想连接到名称空间,我无法连接。我做错了什么?

我做了一个小程序,显示了我的问题:

### removed to make the post less long, see below ###

我很确定我连接错了客户端。但我不知道该怎么做。我查看了 SocketIO Client 文档,但找不到帮助。

编辑:


为了更清楚,这是一个只有一个插座的更新版本:

from flask import Flask
from flask_socketio import SocketIO

app = Flask(__name__)
socketio = SocketIO(app)

@socketio.on("connect", namespace="/test")
def handle_connect():
   print("heureka!")
   return True

@app.route('/')
def index():
    return """
<!DOCTYPE HTML>
<html>
<head>
    <title>Flask-SocketIO Test</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
        var socket1 = io("http://127.0.0.1:5000/test");
        socket1.on("connect", function() {
            console.log("yay!")
        });
    </script>
</head>
<body>
    Testing
</body>
</html>
"""

socketio.run(app, debug=True, log_output=True, use_reloader=False)

我可以在我的终端中看到套接字发送的请求:

(6548) wsgi starting up on http://127.0.0.1:5000
(6548) accepted ('127.0.0.1', 59354)
127.0.0.1 - - [30/Dec/2020 19:15:58] "GET / HTTP/1.1" 200 691 0.000000
127.0.0.1 - - [30/Dec/2020 19:15:58] "GET /socket.io/?EIO=4&transport=polling&t=NQqtHrO HTTP/1.1" 200 371 0.000997
127.0.0.1 - - [30/Dec/2020 19:15:59] "GET /socket.io/?EIO=4&transport=polling&t=NQqtI28 HTTP/1.1" 200 371 0.000997
127.0.0.1 - - [30/Dec/2020 19:16:00] "GET /socket.io/?EIO=4&transport=polling&t=NQqtILH HTTP/1.1" 200 371 0.000000
127.0.0.1 - - [30/Dec/2020 19:16:03] "GET /socket.io/?EIO=4&transport=polling&t=NQqtJ0u HTTP/1.1" 200 371 0.000996
127.0.0.1 - - [30/Dec/2020 19:16:08] "GET /socket.io/?EIO=4&transport=polling&t=NQqtKFD HTTP/1.1" 200 371 0.001002
127.0.0.1 - - [30/Dec/2020 19:16:13] "GET /socket.io/?EIO=4&transport=polling&t=NQqtLTa HTTP/1.1" 200 371 0.001024

您使用的 path 选项不是指定命名空间,它用于指示自定义 Socket.IO 端点。一般情况下不需要设置路径。

命名空间在连接中给出URL:

var socket1 = io("/test");

或者如果你更喜欢绝对 URL:

var socket1 = io("http://localhost:5000/test");