I built a little demo to try out bidirectional communication via WebSockets in FLASK, which worked ok. Now I am trying to do the same setup with FastAPI (and fastapi-socketio instead of flask-socketio) which fails to connect. Has anyone an idea what I am doing wrong? Thank you in advance.
Errors in Terminal:
INFO:127.0.0.1:50117 - "GET / HTTP/1.1" 200 OK
INFO:127.0.0.1:50117 - "GET /socket.io/?EIO=4&transport=polling&t=NeEnmWx HTTP/1.1" 404 Not Found
Errors in Console:
Failed to load resource: the server responded with a status of 404 (Not Found)
polling-xhr.js:202
GET http://127.0.0.1:8000/socket.io/?EIO=4&transport=polling&t=NeEnoe_ 404 (Not Found)
index.html:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.1.3/socket.io.js"
integrity="sha512-2RDFHqfLZW8IhPRvQYmK9bTLfj/hddxGXQAred2wNZGkrKQkLGj8RCkXfRJPHlDerdHHIzTFaahq4s/P4V6Qig=="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<script type="text/javascript">
$(document).ready(function () {
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('connect', function (event) {
console.log('user is connected now');
socket.emit('client_connect_event', { data: 'User connected' });
});
socket.on('server_antwort_01', function (msg, cb) {
$('#log0').append('<br>' + $('<div/>').text('logs #' + msg.count + ': ' + msg.data).html());
if (cb)
cb();
});
$('form#start').submit(function (event) {
socket.emit('client_start_event', { data: 'Start doing something' });
return false;
});
$('form#stop').submit(function (event) {
socket.emit('client_stop_event', { data: 'Stop doing something' });
return false;
});
});
</script>
<h1>Websocket Demo</h1>
<h2> Press below to display something send from Server</h2>
<form id="start" method="post" action="#">
<input type="submit" value="Start">
</form>
<form id="stop" method="post" action="#">
<input type="submit" value="Stop">
</form>
<h3> Log </h3>
<div id="log0"></div>
</body>
</html>
mainSocket.py (with FastAPI)
from fastapi import FastAPI
from fastapi_socketio import SocketManager
from fastapi.responses import HTMLResponse
app = FastAPI()
socket_manager = SocketManager(app=app)
html = ""
with open('index.html', 'r') as f:
html = f.read()
@app.get("/")
async def get():
return HTMLResponse(html)
@app.sio.on('client_connect_event')
async def handle_client_connect_event(message):
print(message)
await app.sio.emit('server_antwort01', {'data': 'connection was successful'})
@app.sio.on('client_start_event')
async def handle_client_start_event(message):
print('Server says: start_event worked')
print(message)
await app.sio.emit('server_antwort01',{'data':'start event worked'})