'Socket.IO with Python + React
I am making a web app and wanted to use React for the frontend and Python for the backend and Socket.IO to communicate between the two.
I tried to get a simple setup and establish a connection between the frontend and backend but I am running into issues.
Here is my barebones server implementation that I run using gunicorn on http://127.0.0.1:8000.
import socketio
# Create a Socket.IO server and WSGI application
sio = socketio.Server(cors_allowed_origins='*')
app = socketio.WSGIApp(sio)
@sio.event
def connect(sid, environ):
print('connected!', sid)
In React, I have the sockets.js file.
import io from 'socket.io-client';
export const socket = io(
'http://127.0.0.1:8000',
{ transports: ['websocket', 'polling', 'flashsocket'] },
);
I try to use this socket variable in App, but it does not work.
import { Route, Routes } from 'react-router-dom';
import { Home } from "./Home"
import { socket } from '../services/sockets';
export default function App() {
socket.emit("hello")
return (
<Routes>
<Route path="/" element={<Home />} />
</Routes>
)
}
I see the following errors in the console.
WebSocket connection to 'ws://127.0.0.1:8000/socket.io/?EIO=3&transport=websocket' failed:
In terms of versions, I am on python-socketio==5.5.1 and on "socket.io-client": "^4.4.1".
Would love your help on the best way to establish this connection between the backend and frontend. Let me know if you have any more questions.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
