0

我的反应组件:

import React, { useState, useEffect } from 'react';
import {Redirect} from "react-router-dom";
import io from "socket.io-client";

function Game({userName, roomCode}) {

    const [users, setUsers] = useState([])

    useEffect(() => {
        const socket = io("http://127.0.0.1:5000")
        socket.emit('join', {userName, roomCode})
        socket.on('message', (msg) => console.log(msg))
        socket.on('updateUsers', (userlist) => {
            setUsers(Object.values(userlist))
        }) 
        return () => {
            socket.disconnect()
        }
        }, [])

    const userItems = users.map((element) =>
        <li>{element.username}</li>)

    return userName === '' ? <Redirect to="/"/> :
        (
        <div>
            <h1>Game Page</h1>
            <h2>Users:</h2>
            <ul>{userItems}</ul>
        </div>
    );
}

export default Game;

烧瓶:

from flask import Flask, render_template, request
from flask_socketio import SocketIO, send, join_room, leave_room, emit
from users import UserDB

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, cors_allowed_origins="*")

db = UserDB()

@socketio.on('join')
def on_join(data):
    print("Joining!")
    username = data['userName']
    room = data['roomCode']
    join_room(room)
    db.add_user(request.sid, username, room)
    room_list = db.get_room_users(room)
    emit('updateUsers', room_list, broadcast=True, room=room)


@socketio.on('disconnect')
def on_leave():
    user = db.delete_user(request.sid)
    room = user['room']
    room_list = db.get_room_users(room)
    emit('updateUsers', room_list, broadcast = True, room = room)
    print('disconnection!')


if __name__ == '__main__':
    socketio.run(app, debug=True)

现在,如果我按回浏览器(使用 React Router),组件会卸载并且套接字会立即断开连接。但是,如果我关闭选项卡,套接字只会在大约一分钟后断开连接。我该如何做到这一点,以便在浏览器/选项卡关闭时套接字断开连接(它在 Vanilla JS 上的工作方式)?

4

1 回答 1

0

见文档烧瓶-socketio

编辑 ping_timeout 和 ping_interval 选项以找到适当的答案。

socketio = SocketIO(app, cors_allowed_origins="*")

于 2020-07-09T05:39:46.593 回答