没有建立从 react socket-io 客户端到 flask-socket-io 服务器的连接以进行实时更新

Connection is not getting established from react socket-io client to flask-socket-io server for real time update

仅出于学习目的,我正在尝试使用 SOCKET.io 在 React 和 Flask 之间建立 连接以获取实时更新。

但是,遗憾的是我无法在客户端socket.io之间建立连接以切断socket.io直到现在

我关注了几个博客并探索了 GitHub 个问题,但其中 none 个对我有所帮助。

代码

1.反应代码

    import React, { useState, useEffect } from "react";
    import socketIOClient from "socket.io-client";
    import io from "socket.io-client/dist/socket.io";
    import "./App.css";
    
    const ENDPOINT = "http://127.0.0.1:5000";
    
    function App() {
      const [data, setData] = useState("");
    
      const setRecords = (response) => {
        console.log("response", response);
        setData(response.records);
      };
      useEffect(() => {
        // const socket = socketIOClient(ENDPOINT);   // >>>>> Not Working
        const socket = io.connect(ENDPOINT, { rejectUnauthorized: false }); //{ transports:["websocket"]}
        console.log("connected", socket);
        socket.on("success", (data) => console.log(data));
   
        // socket.on("FetchRecords");
        // socket.emit("FetchRecords");
        // socket.on("SendingRecords", setRecords);
    
        // socket.on("FromAPI", data => {
        //   setResponse(data);
        // });
      }, []);
      return (
        <div className="App">WEBSOCKET with FLASK and REACT...{data.length}</div>
      );
    }
    
    export default App;

现在,如果我在控制台中看到日志,则说明正在断开连接。

2。后端代码

from flask import Flask, jsonify
from mongoConnect import todo
from flask_socketio import SocketIO, send, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins='*', engineio_logger=True)

@socketio.on('connect')
def test_connect():
    print('CONNECT EVENT happened...')
    emit('success', {'data': 'Connected'})


@socketio.on('FetchRecords')
def fetch_all_records():
    records = todo.find({})
    print('fetch_all_records', len(records))
    response = jsonify({'code': 200, 'records': records})
    print(response)
    emit('sendingRecords', response)


if __name__ == '__main__':
    socketio.run(app, port=5000)

后端日志(使用 geevent-websocket)

谁能告诉我哪里错了?奇怪的是 none 他们中有像我这样的问题...... 这是我检查过的博客和问题...

1. React Native: unable to establish the socket connection
2. Simple Chat-App with React & Flask
3.Socket.IO, React and Node.js: Going Real-Time

我也遇到了同样的问题

尝试卸载socket.io-客户端并安装2.3.1版本npm i socket.io-client@2.3.1

旧版本适合我。

另一件事是确保在您尝试连接的同一端口上没有其他服务器运行。

简单的错误,但它可能会发生