Reputation: 1624
Just for learning purpose, I am trying to establish a connection between react and flask with SOCKET.io to get real time updates.
But, sadly I am not able to establish a connection between client socket.io to sever socket.io till now.
I followed several blogs and explored GitHub issues, but none of them had helped me.
Codes
1. React codes
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;
Now if I see the logs in the console, it is being disconnected.
2. Backend Code
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)
Logs of backend (using geevent-websocket)
Can anyone tell me where am I going wrong? Weirdly none of them had the problem like me... Here are the blogs and issues I checked...
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
Upvotes: 1
Views: 2792
Reputation: 11
Another thing is to make sure there isn't another server running on the same port you're trying to connect to.
Simple mistake but it could happen
Upvotes: 0
Reputation: 34
I had the same problem too.
Try uninstall socket.io-client and install version 2.3.1 npm i [email protected]
The old version works for me.
Upvotes: 1