node.js - 如何在更改 url 时保持套接字连接处于活动状态
问题描述
在前端(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 更改时断开连接
解决方案
套接字连接将在重定向时丢失,因为套接字连接在Form
尝试将其向上移动App.js
并通过道具或上下文传递套接字变量
推荐阅读
- git - 无法在 Rundeck 上启用 SCM Git 导入
- css - 是否可以避免更改我的 CSS,即使是不希望的 * 重置?
- linux - 如何验证两个检查点之间是否已释放所有内存分配?
- r - 如何在时间 = 0 时添加结果的基线值作为混合效应模型中的固定效应?
- vba - 我想过滤除数组中的值之外的所有值
- amazon-rds - 如何使用 AWS 数据管道解决“找不到数据库的 DriverClass:mariadb”?
- typescript - Accessing Interface in Type Definition File That is Not Exported (Cache Interface in @types/cache-manager)
- react-native - 文本输入闪烁反应本机
- git - 如何将分叉的 GitHub 存储库中的功能分支加载到我的应用程序中?
- java - 为什么 list-iterator.next(); 除非重复多次直到结束,否则返回“无当前元素”位置?