【问题标题】:Setting custom ID on signalR core start在 signalR 核心启动时设置自定义 ID
【发布时间】:2020-02-04 11:51:57
【问题描述】:

我正在构建一个涉及 1:1 客户和管理员会话的应用。 我正在使用 opentok 将客户与管理员联系起来,并为他们的会话创建一个唯一 ID。 将有多个客户:管理员会话,但每个会话应该是唯一的。

我正在使用 React 和 asp.net core 3。

我希望能够在客户和管理员之间建立私人 Signal R 连接。没有授权设置,这一切都基于他们将在查询字符串中给出的唯一 ID。

目前我在 React 中连接到 Signal R,如下所示:

import { HubConnectionBuilder } from '@aspnet/signalr';
import { useState, useEffect } from "react";
import config from "config.js";

export default function useSignalR() {
    const [hubConnection, setHubConnection] = useState(null);  

    useEffect(() => {
        //ideally ill supply the connection a guid here
        let connectionBuilder = new HubConnectionBuilder()
            .withUrl(config.signalRServerUrl)
            .build();

        setHubConnection(connectionBuilder);
        connectionBuilder.start()
            .then(() => console.log("signalr connection started"))
            .catch((err) => console.log("Error while establishihng connection ", err));
    }, []);

    return hubConnection;
}

管理员和客户正在使用相同的功能连接到asp.net core signal R hub,目前看起来是这样的:

public class PhotoHub : Hub
{
    public async Task TakeSnapShot()
    {
        await Clients.All.SendAsync("takeSnapShot");
    }
}

我想它会是这样的:

仅限伪代码

 //in javascript connection
  let connectionBuilder = new HubConnectionBuilder()
        .withProperty(uniqueId)   //pseudo code
        .withUrl(config.signalRServerUrl)
        .build();

public class PhotoHub : Hub
{
    public async Task TakeSnapShot(uniqueId)
    {
       var clientsInSession = Clients.where(customId == uniqueId); //pseudo code  
       foreach (var client in clientsInSession){
           await client.SendAsync("takeSnapShot");   //pseudo code
       }
    }
}

【问题讨论】:

    标签: javascript c# reactjs asp.net-core signalr


    【解决方案1】:

    当您使用集线器中的此代码连接到集线器时,SignalR 已经提供了唯一的连接 ID

        public string GetConnectionId()
        {
            return Context.ConnectionId;
        }
    

    所以你可以这样调用

     var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();
    
            connection.start().then(function () {
                console.log("connected");
    
                connection.invoke('getConnectionId')
                    .then(function (connectionId) {
                        console.log(connectionId)
                    }).catch(err => console.error(err.toString()));;
    
            });
    

    【讨论】:

    • 我想我可以在这里包含我的会话 ID 和连接 ID,例如“GetConectionId(string sessionId).. 然后存储一个全局静态字典 sesionId->ConnectionId..
    • 是的,您可以这样做,但使用会话存储来存储连接 ID 是一种不错的方法
    • @michael 你也可以投票赞成我的答案吗?谢谢。
    • @michael 和 @TonyNgo - 供将来参考:Rejected Edit 建议使用 connectionId; 此编辑旨在解决帖子的作者,作为编辑毫无意义。它应该写成评论或答案。
    猜你喜欢
    • 2018-11-14
    • 2016-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    • 2019-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多