无法在信号r 2.4.0中向特定客户端发送请求

时间:2018-12-12 11:18:21

标签: javascript c# signalr signalr-hub

我已经创建了一个信号集线器,并正在尝试向特定用户发送通知,该用户的connectionId我已经拥有,但未收到用户端的回调。 这是javascript代码

 con = $.connection.opinionHub;


//dummy function to initialize connection
con.client.foo = function () { };

$.connection.hub.start().done(function () {

    if (typeof requestId !== 'undefined') {

        con.server.isUserOnline(requestId)
                  .done().fail(function (err) {
                      $('#lnkVideo').removeClass('active').removeAttr('href');
                      console.log('isUserOnline failed: ' + err);
                  });

        if (IsDoc === true) {
            alert('Is Doctor');
            con.client.isPatientOnline = function (response) {
                alert('Patient Online');
                console.log(response);
                if (response=== true) {
                    $('#lnkVideo').addClass('active').attr('href', 'http://localhost:8093/Connect?RequestId=' + requestId);
                }
                else {
                    $('#lnkVideo').removeClass('active').removeAttr('href');
                }
            };
        }

        if (IsPat === true) {
            alert('Is Patient');
            con.client.isDoctorOnline = function (response) {
                alert('Doctor Online');
                console.log(response);
                if (response=== true) {
                    $('#lnkVideo').addClass('active').attr('href', 'http://localhost:8093/Connect?RequestId=' + requestId);
                }
                else {
                    $('#lnkVideo').removeClass('active').removeAttr('href');
                }
            };
        }

            con.server.isUserOnline(requestId)
                .done().fail(function (err) {
                    $('#lnkVideo').removeClass('active').removeAttr('href');
                    console.log('isUserOnline failed: ' + err);
                });
    }

});

我在OnConnected上保存了用户connectionId。 isPatientOnline和isDoctorOnline是中心的动态方法。 isUserOnline是集线器中定义动态方法的方法。

问题是当用户连接到集线器时,connectionId被注册,并且稍后当另一个具有相同requstId的用户连接但客户端未收到该通知时,我会向connectionId发送通知。

因此,当用户连接到传递requestId的集线器时,我会根据角色向医生或用户发送通知。因此,在当前用户端,我收到通知,但在第二用户端,则什么也没发生。

这是中心代码

[Authorize]
public class OpinionHub : Hub
{
    private readonly static ConnectionMapping<string> _connections =
      new ConnectionMapping<string>();
    static HttpClient client = new HttpClient();


    public async Task UserRegistered()
    {

    }

    public async Task IsUserOnline(int RequestId)
    {
        List<ParticipantDetailsVM> lst = null;
        try
        {

            var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.Remove("Authorization");
            client.DefaultRequestHeaders.Add("Authorization", identity.FindFirst("AcessToken").Value);
            var httpResponseMessage = await client.GetAsync(Constant.ApiBaseUri + "Request/GetParticipantsAsync?RequestId=" + RequestId);


            if (httpResponseMessage.IsSuccessStatusCode)
            {
                var result = await httpResponseMessage.Content.ReadAsStringAsync();
                MethodResultVM<ParticipantDetailsVM> methodResult = JsonConvert.DeserializeObject<MethodResultVM<ParticipantDetailsVM>>(result);
                lst = methodResult.Result;

            }

            var DoctorConnectionIds = _connections.GetConnections(lst[0].DoctorId.ToString());
            var UserConnectionIds = _connections.GetConnections(lst[0].PatientId.ToString());

            if (lst[0].RequestAccepted == false) // if request is pending or rejected , no need to enable cam , send false
            {
                foreach (string con in DoctorConnectionIds)
                {
                    Clients.Client(con).isPatientOnline(false);

                }

                foreach (string con in UserConnectionIds)
                {
                    Clients.Client(con).isDoctorOnline(false);
                }
            }
            else
            {
                if (DoctorConnectionIds.Count() > 0 && UserConnectionIds.Count() > 0) // both doctor and patient online
                {
                    foreach (string con in DoctorConnectionIds)
                    {
                        Clients.Client(con).isPatientOnline(true);

                    }

                    foreach (string con in UserConnectionIds)
                    {
                        Clients.Client(con).isDoctorOnline(true);
                    }
                }
                else if (DoctorConnectionIds.Count() > 0 && UserConnectionIds.Count() == 0) // doctor online  and parient offline
                {
                    foreach (string con in DoctorConnectionIds)
                    {
                        Clients.Client(con).isPatientOnline(false);

                    }
                }
                else if (DoctorConnectionIds.Count() == 0 && UserConnectionIds.Count() > 0) // doctor offline and patient online
                {
                    foreach (string con in UserConnectionIds)
                    {
                        Clients.Client(con).isDoctorOnline(false);
                    }
                }
            }




        }
        catch (Exception ex)
        {

        }

    }


    public override Task OnConnected()
    {

        var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
        var UserId = identity.FindFirst("UserId").Value;

        _connections.Add(UserId, Context.ConnectionId);

        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {

        var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;

            var id = Context.ConnectionId;
            var UserId = _connections.GetUserIdFormConnect(id);
            _connections.Remove(UserId, Context.ConnectionId);


        return base.OnDisconnected(stopCalled);
    }

    public override Task OnReconnected()
    {

        var identity = (ClaimsPrincipal)Thread.CurrentPrincipal;
        var UserId = identity.FindFirst("UserId").Value;



        if (!_connections.GetConnections(UserId).Contains(Context.ConnectionId))
        {
            _connections.Add(UserId, Context.ConnectionId);
        }

        return base.OnReconnected();
    }
}

0 个答案:

没有答案