在前端(reactjs)上,我有在加入房间之前提交数据的表单,因为数据必须经过验证,所以我有 onSubmit 函数可以做到这一点,如果一切正常,则将用户重定向到 /drawing-page
,当发生套接字断开连接(socket.on('disconnect') 在后端触发)。
import { io } from 'socket.io-client';
const socket = io('http://localhost:8080');
export const formValidation = (username, room) => {
if (!username || !room) {
alert('Room and username must be provided');
return false;
}
if (username.length < 4 || room.length < 4) {
alert('Room and username must be at least 4 characters long');
return false;
}
if (username.length > 30 || room.length > 30) {
alert('Room and username can\'t be longer than 30 characters');
return false;
}
return true;
}
const onSubmit = e => {
e.preventDefault();
const username = e.target.username.value;
const room = e.target.room.value;
if (!formValidation(username, room)) {
return;
}
socket.emit('join', { username, room }, error => {
if (error) {
alert(error);
window.location.href = '/';
}
});
window.location.href = '/drawing-page';
}
后端代码:
socket.on('disconnect', reason => {
console.log(`reason: ${reason}`);
const user = removeUser(socket.id);
if (user) {
if (!io.sockets.adapter.rooms.get(user.room)) {
removeRoom(user.room);
io.emit('showActiveRooms', getRooms());
}
}
});
由于 URL 更改,套接字断开连接,有什么方法可以使套接字断开连接仅在应用程序关闭时而不是在 url 更改时断开
答案 0 :(得分:1)
套接字连接将在重定向时丢失,因为套接字连接位于 Form
尝试将其向上移动到 App.js
并通过 props 或上下文传递套接字变量