我有一个FastAPI Python服务器,它支持sockets连接。我尝试使用socket.io-client通过React客户端连接。问题是socket创建正确,但之后立即关闭。这是Python服务器如何提供连接到sockets的接口:
import socketio
sio = socketio.AsyncServer(cors_allowed_origins="*", async_mode="asgi")
# define an asgi app
socketio_app = socketio.ASGIApp(sio, socketio_path="/")
@sio.event
async def connect(sid, environ):
print("connect ", sid)
player_id = environ.get("HTTP_PLAYER_ID")
game_id = environ.get("HTTP_GAME_ID")
# if the parameters are not present, the connection is rejected
if not player_id or not game_id:
return False
await s
io.save_session(sid, {"player_id": player_id, "game_id": game_id})
sio.enter_room(sid, "g" + game_id)
sio.enter_room(sid, "p" + player_id)
print("connect ", sid, "player_id ", player_id, "game_id ", game_id)
字符串
然后,它被安装到应用程序中,如下所示:
app.mount("/socket.io", socketio_app)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
型
这是我创建套接字的客户端文件:
import { io } from "socket.io-client"
// hardcoded values for headers
const gameId = 1;
const playerId = 1;
const createSocket = (uri) => {
const socket = io(uri, {
extraHeaders: {
game_id: gameId,
player_id: playerId
},
transports: ["websocket"],
autoConnect: true,
// Listen for events
socket.on("connection", () => console.log("websocket connected"));
return socket;
}
const gameSocket = createSocket("http://localhost:8000/")
export {gameSocket};
型
然后将创建的套接字导入此文件:
import { gameSocket } from "./createSocket"
import { useState, useEffect } from "react"
const useSocket = () => {
const [connected, setConnected] = useState(true);
const handleConnChange = () => {
setConnected(gameSocket.connected)
}
useEffect(() => {
gameSocket.on("connect", handleConnChange);
gameSocket.on("disconnect", handleConnChange);
return () => {
gameSocket.removeListener("connect", handleConnChange);
gameSocket.removeListener("disconnect", handleConnChange);
}
})
return {
gameSocket: gameSocket,
isConnected: connected
}
}
export default useSocket;
型
我最终在这个组件中使用了“useSocket”:
import { useEffect, useRef, useState } from "react"
import useSocket from "./useSocket";
const GameRouter = () => {
const [gameState, setGameState] = useState(-1);
const [gameData, setGameData] = useState({});
const [playerData, setPlayerData] = useState({});
const { gameSocket } = useSocket();
useEffect(() => {
gameSocket.on("game_status", (data) => {
setGameData(data);
setGameState(data.state)
})
}, [gameData])
return {
<h1>websockets test<h1/>
}
}
export default GameRouter;
型
当服务器和客户端都运行时,这是我从服务器获得的日志:
INFO: connection open
connect UrwFItMNGGWN4FLaAAAT
INFO: connection closed
型
如果有人能帮我我会很感激的。谢谢。
似乎套接字创建断开连接。我尝试设置autoConnect字段为false,并手动调用socket.connect()方法,但没有工作。我检查了我用于服务器和客户端的socketio版本是否兼容。这些是唯一修改或创建套接字的文件。没有额外的组件渲染,以便隔离环境来测试连接工作。
1条答案
按热度按时间enyaitl31#
我有完全相同的问题,它似乎像服务器是不正确解析您发送的头.尝试发送这些值作为查询而不是作为一个头.然后相应地修改服务器代码.有一个伟大的一天!