【问题标题】:How to keep socket connection alive using when changing url如何在更改 url 时保持套接字连接处于活动状态
【发布时间】:2021-07-31 06:16:33
【问题描述】:

在前端(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 更改时断开连接

【问题讨论】:

    标签: node.js reactjs socket.io routes keep-alive


    【解决方案1】:

    由于套接字连接在Form 中,套接字连接将在重定向时丢失尝试将其向上移动到App.js 并通过道具或上下文传递套接字变量

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 2018-04-13
      • 1970-01-01
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-03
      相关资源
      最近更新 更多