【问题标题】:React .NET - Display all active connections with SignalRReact .NET - 使用 SignalR 显示所有活动连接
【发布时间】:2022-10-04 20:34:11
【问题描述】:

我正在使用一个使用 React 作为前端和 .net 作为后端的应用程序。

现在我正在尝试将连接添加为一个数字,以向用户显示应用程序现在有多少人处于活动状态,我希望这个数字能够实时更新,我正在使用 SignalR。

发生的情况是当 1 个用户处于活动状态时,它显示 3 而不是显示 1。当 2 个用户处于活动状态时,它显示 6-7 并继续这样。

让我给你看一些代码

OnConnectionCountHub.cs

public class OnConnectionHub : Hub
{
    public static int ConnectionCount { get; set; }

    public override Task OnConnectedAsync()
    {
        ConnectionCount++;
        Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        ConnectionCount--;
        Clients.All.SendAsync("updateConnectionCount", ConnectionCount).GetAwaiter().GetResult();
        return base.OnDisconnectedAsync(exception);
    }
}

相当简单。

连接计数.tsx

export const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    // create connection
    useEffect(() => {
        const connection = new HubConnectionBuilder()
        .withUrl(urlOnConnectionHub)
        .build()

    // connect to method that hub invokes
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
        }
    )

    // start connection
    connection.start().then(() => {
        console.log("Connection started")
    });
    }, [])
    

    return(
        <section>
            <p>Active users: {connectionCount}</p>
        </section>
    )
}

我的猜测是,因为这是一个组件,它在我使用该组件的地方获得了两倍的连接,而不是一个连接。

关于如何解决这个问题的任何想法? UseContext 可能吗?

【问题讨论】:

    标签: c# reactjs asp.net-core signalr-hub react-tsx


    【解决方案1】:

    在客户端试试这个:

    export  const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    
    const connection = new HubConnectionBuilder()
    .withUrl(urlOnConnectionHub)
    .build()
    
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
     });
    
    useEffect(() => {        
          if (connection.state === HubConnectionState.Disconnected){
                connection.start().then(() => {
                    console.log("Connection started")
                });
            }                     
        }, []);
    
         return(
             <section>
                <p>Active users: {connectionCount}</p>
             </section>
      )
    }
    

    【讨论】:

    • 感谢您的回答,遗憾的是它没有用。
    • 我测试了它,没有问题,现在发生了什么?
    • 你是对的,这确实有效。但是,为了让它工作,我不能将它用作可重复使用的组件,但我需要将它直接添加到我想使用它的网站的主页中。但它仍然有效,谢谢朋友!
    • 在我尝试了一段时间后,遗憾的是它仍然像以前一样工作。当想要在另一个组件上创建另一个连接时,它会加倍而不是仅添加 1 个新连接
    【解决方案2】:

    这个错误的解决方案是useContext

    我遇到的错误是,在我使用带有 signalR 的组件的每个地方都建立了连接。

    该组件不起作用:

    export  const ConnectionCount = () => {
    const [connectionCount, setConnectionCount] = useState(0)
    
    const connection = new HubConnectionBuilder()
    .withUrl(urlOnConnectionHub)
    .build()
    
    connection.on("updateConnectionCount", (onConnection) => {
        setConnectionCount(onConnection)
     });
    
    useEffect(() => {        
          if (connection.state === HubConnectionState.Disconnected){
                connection.start().then(() => {
                    console.log("Connection started")
                });
            }                     
        }, []);
    
         return(
             <section>
                <p>Active users: {connectionCount}</p>
             </section>
      )
    }
    

    但我创建了一个上下文:

    import React from 'react'
    
    const ConnectContext = React.createContext({
        connectionCount: 0
    });
    
    export default ConnectContext;
    

    我还创建了一个上下文提供程序,其中我从 signalR 组件中获取了所有逻辑:

    export const ConnectContextProvider = (props: ConnectContextProviderProps) => {
        const [connectionCount, setConnectionCount] = useState(0)
        
        const connection = new HubConnectionBuilder()
        .withUrl(urlOnConnectionHub)
        .build()
        
        connection.on("updateConnectionCount", (onConnection) => {
             setConnectionCount(onConnection)
         });
        
        useEffect(() => {        
              if (connection.state === HubConnectionState.Disconnected){
                    connection.start().then(() => {
                        console.log("Connection started")
                    });
                }                     
            // eslint-disable-next-line react-hooks/exhaustive-deps
            }, []);
    
            return <ConnectContext.Provider value={{connectionCount: connectionCount}}>{props.children}</ConnectContext.Provider>
    }
    
    interface ConnectContextProviderProps {
        children: ReactElement;
    };
    

    在前面的 signalR 组件中,我写了这个:

    export const ConnectionCount = () => {
        
        const connectCtx = useContext(ConnectContext)
        return <p>Active Users - {connectCtx.connectionCount}</p>
    }
    

    现在我可以使用这个组件,而无需在任何地方获得新的连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多