我正在使用react、node.js 和socket.io 构建一个聊天应用程序。
我有以下用于连接和断开连接的钩子
useEffect(() => {
const { name, room } = queryString.parse(location.search)
socket = io(ENDPOINT)
setRoom(room)
// New user joins room
socket.emit('join', { name, room }, (userNamesPresent, error) => {
setUsersPresent(userNamesPresent.userNamesPresent)
})
return () => {
// User leaves room
socket.emit('disconnect')
socket.off()
}
}, [ENDPOINT, location.search])
Run Code Online (Sandbox Code Playgroud)
我像这样在节点中处理它
io.on("connection", socket => {
socket.on("join", ({ name, room }, callback) => {
const { error, user } = addUser({id: socket.id, name, room})
if(error) {
return callback({error})
}
// Emitting a welcome …Run Code Online (Sandbox Code Playgroud)