75 lines
2.2 KiB
Python
75 lines
2.2 KiB
Python
import socketio
|
|
from fastapi import FastAPI
|
|
from fastapi.responses import HTMLResponse
|
|
|
|
# 1. Create the FastAPI app
|
|
app = FastAPI()
|
|
|
|
# 2. Create the Socket.IO server (Async mode for FastAPI)
|
|
sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins='*')
|
|
|
|
# 3. Wrap FastAPI with Socket.IO
|
|
# This allows 'socket_app' to handle socket traffic and pass
|
|
# everything else to 'app'
|
|
socket_app = socketio.ASGIApp(sio, app)
|
|
|
|
# --- Socket.IO Events ---
|
|
|
|
@sio.event
|
|
async def connect(sid, environ):
|
|
print(f"Client connected: {sid}")
|
|
await sio.emit('response', {'data': 'Connected to Server!'})
|
|
|
|
@sio.event
|
|
async def message(sid, data):
|
|
print(f"Received from {sid}: {data}")
|
|
# Broadcast to everyone (including sender)
|
|
await sio.emit('response', {'data': f"Echo: {data}"})
|
|
|
|
@sio.event
|
|
async def disconnect(sid):
|
|
print(f"Client disconnected: {sid}")
|
|
|
|
# --- FastAPI Routes ---
|
|
|
|
html_client = """
|
|
<!DOCTYPE html>
|
|
<html>
|
|
<head>
|
|
<title>FastAPI Socket.IO Test</title>
|
|
<!-- Load Socket.IO Client from CDN -->
|
|
<script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
|
|
<script>
|
|
const socket = io();
|
|
|
|
socket.on('connect', () => {
|
|
document.getElementById('status').innerText = 'Connected: ' + socket.id;
|
|
document.getElementById('status').style.color = 'green';
|
|
});
|
|
|
|
socket.on('response', (data) => {
|
|
const li = document.createElement("li");
|
|
li.innerText = JSON.stringify(data);
|
|
document.getElementById("messages").appendChild(li);
|
|
});
|
|
|
|
function sendMessage() {
|
|
const input = document.getElementById("msg");
|
|
socket.emit('message', input.value);
|
|
input.value = "";
|
|
}
|
|
</script>
|
|
</head>
|
|
<body>
|
|
<h1>Socket.IO Test</h1>
|
|
<h3 id="status" style="color:red">Disconnected</h3>
|
|
<input id="msg" type="text" placeholder="Type a message..." />
|
|
<button onclick="sendMessage()">Send</button>
|
|
<ul id="messages"></ul>
|
|
</body>
|
|
</html>
|
|
"""
|
|
|
|
@app.get("/")
|
|
async def index():
|
|
return HTMLResponse(html_client) |