【问题标题】:Can't receive messages from groups Ng-Chat无法接收来自群组 Ng-Chat 的消息
【发布时间】:2019-02-26 22:03:46
【问题描述】:

我已经实现了 ng-chat https://github.com/rpaschoal/ng-chat (SignalR)。

我有 3 个用户:User1、User2 和 User3

如果我从用户 1 向用户 2 发送消息,它工作正常用户 2 接收消息,但如果我创建一个组(与用户 1 我打开用户 2 的聊天,然后添加用户 3)一个新组与用户(用户 2 和用户 3 )。

所以,当我从这个新聊天中发送消息时,用户(用户 2 和用户 3)没有收到任何消息

这是我的 SingalR 集线器:

using AdvansysOficina.Api._Core.Infraestructura;
using AdvansysOficina.Api.Generales.Servicios.UsuarioNs;
using Microsoft.AspNetCore.SignalR;
using NgChatSignalR.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AdvansysOficina.Api.Desarrollo.Servicios.ConversacionPuntoNs.HubNs
{
public class ConversacionHub : Hub
{
    private static List<ParticipantResponseViewModel> AllConnectedParticipants { get; set; } = new List<ParticipantResponseViewModel>();
    private static List<ParticipantResponseViewModel> DisconnectedParticipants { get; set; } = new List<ParticipantResponseViewModel>();
    private readonly object ParticipantsConnectionLock = new object();

    private ISesion _sesion;
    private IUsuarioServicio _usuarioServicio;

    public ConversacionHub(ISesion sesion, IUsuarioServicio usuarioServicio)
    {
        _sesion = sesion;
        _usuarioServicio = usuarioServicio;
    }

    public static IEnumerable<ParticipantResponseViewModel> ConnectedParticipants(string currentUserId)
    {
        return AllConnectedParticipants
            .Where(x => x.Participant.Id != currentUserId);
    }

    public void Join(string userName, dynamic grupo)
    {
        lock (ParticipantsConnectionLock)
        {
            AllConnectedParticipants.Add(new ParticipantResponseViewModel()
            {
                Metadata = new ParticipantMetadataViewModel()
                {
                    TotalUnreadMessages = 0
                },
                Participant = new ChatParticipantViewModel()
                {
                    DisplayName = userName,
                    Id = Context.ConnectionId,
                }
            });


            // This will be used as the user's unique ID to be used on ng-chat as the connected user.
            // You should most likely use another ID on your application
            //Clients.Caller.SendAsync("generatedUserId", Context.ConnectionId);

            Clients.Caller.SendAsync("generatedUserId", Context.ConnectionId);

            Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
        }
    }

    public void SendMessage(MessageViewModel message)
    {

        var sender = AllConnectedParticipants.Find(x => x.Participant.Id == message.FromId);

        if (sender != null)
        {
            Clients.Client(message.ToId).SendAsync("messageReceived", sender.Participant, message);
        }
    }

    public override Task OnDisconnectedAsync(Exception exception)
    {
        lock (ParticipantsConnectionLock)
        {
            var connectionIndex = AllConnectedParticipants.FindIndex(x => x.Participant.Id == Context.ConnectionId);

            if (connectionIndex >= 0)
            {
                var participant = AllConnectedParticipants.ElementAt(connectionIndex);

                AllConnectedParticipants.Remove(participant);
                DisconnectedParticipants.Add(participant);

                Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
            }

            return base.OnDisconnectedAsync(exception);
        }
    }

    public override Task OnConnectedAsync()
    {
        lock (ParticipantsConnectionLock)
        {
            var connectionIndex = DisconnectedParticipants.FindIndex(x => x.Participant.Id == Context.ConnectionId);

            if (connectionIndex >= 0)
            {
                var participant = DisconnectedParticipants.ElementAt(connectionIndex);

                DisconnectedParticipants.Remove(participant);
                AllConnectedParticipants.Add(participant);

                Clients.All.SendAsync("friendsListChanged", AllConnectedParticipants);
            }

            return base.OnConnectedAsync();
        }
    }
}
}

我的 signalR 适配器(角度)

import { ChatAdapter, Message, ParticipantResponse, Group, IChatController } from 'ng-chat';
import { map, catchError } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';

import * as signalR from '@aspnet/signalr';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
import { AlertasHelper } from '../../../shared/helpers/alertas.helper';
import { PushNotificationHelper } from './notifications/push-notification';

export class SignalRAdapter extends ChatAdapter {
  public static serverBaseUrl  =  'http://192.168.16.51:5021/'; // if running locally
  public userId: string;
  private grrupo;
  private hubConnection: signalR.HubConnection;


  constructor(private username: string, private http: HttpClient, private notification: PushNotificationHelper
    ) {
    super();

    this.initializeConnection();
  }

  private initializeConnection(): void {
    this.hubConnection = new signalR.HubConnectionBuilder()
      .withUrl(`${SignalRAdapter.serverBaseUrl}chat`, { transport: signalR.HttpTransportType.LongPolling })
      .build();

    this.hubConnection
      .start()
      .then(() => {
        this.joinRoom();

        this.initializeListeners();
      })
      .catch(err => console.log(`Error while starting SignalR connection: ${err}`));
  }

  private initializeListeners(): void {
    this.hubConnection.on('generatedUserId', (userId) => {
      // With the userId set the chat will be rendered
      this.userId = userId;
    });

    this.hubConnection.on('messageReceived', (participant, message) => {
      // Handle the received message to ng-chat
      console.log(message);
      this.notification.notify('Nuevo mensaje de: ' + participant.displayName, message);
      this.onMessageReceived(participant, message);
    });

    this.hubConnection.on('friendsListChanged', (participantsResponse: Array<ParticipantResponse>) => {
      // Handle the received response to ng-chat
      this.onFriendsListChanged(participantsResponse.filter(x => x.participant.id !== this.userId));
    });
  }

  joinRoom(): void {
    if (this.hubConnection && this.hubConnection.state === signalR.HubConnectionState.Connected) {
      this.hubConnection.send('join', this.username, '');
    }
  }

  listFriends(): Observable<ParticipantResponse[]> {
    // List connected users to show in the friends list
    // Sending the userId from the request body as this is just a demo
    // return this.http
    //   .post(`${SignalRAdapter.serverBaseUrl}listFriends`, { currentUserId: this.userId })
    //   .pipe(
    //     map((res: any) => res),
    //     catchError((error: any) => Observable.throw(error.error || 'Server error'))
    //   );
    return of([]);

  }

  getMessageHistory(destinataryId: any): Observable<Message[]> {
    // This could be an API call to your web application that would go to the database
    // and retrieve a N amount of history messages between the users.
    return of([]);
  }

  sendMessage(message: Message): void {
    if (this.hubConnection && this.hubConnection.state === signalR.HubConnectionState.Connected) {
      console.log(message);
      this.hubConnection.send('sendMessage', message);
    }
  }

  groupCreated(group: Group): void {
    console.log( group);
  }
}

组件的使用

<ng-chat #chat *ngIf="signalRAdapter && signalRAdapter.userId"
  [adapter]="signalRAdapter"
  [userId]="signalRAdapter.userId"
  [groupAdapter]="signalRAdapter"
  (onParticipantChatOpened)="chatOpened($event)"
  [historyEnabled]="false">
</ng-chat>

我已经下载了github的创建者页面的示例,但是他没有使用组的signalr示例,希望您能帮助我。

【问题讨论】:

    标签: c# angular


    【解决方案1】:

    ng-chat 将群组视为个人参与者。调用此事件时,您必须加入您的房间:

    groupCreated(group: Group): void { console.log( group); // Invoke your SignalR hub and send the details of the newly created group }

    ng-chat 将在每次创建组时生成唯一的 id,因此您可以跟踪从正在运行的 ng-chat 实例创建的组是哪个组。如何处理这些组的持久性取决于您的应用程序。

    您可能希望从您的 SignalR 适配器向相关用户推送他们的朋友列表已更改的通知(他们将能够在此阶段看到该组)。您也可以决定不这样做,仅在创建组的用户发送初始消息时才推送通知(再一次,取决于您的应用程序要求和需要)。

    您可能还想在适配器上实现IChatGroupAdapter 以使合同更加明确。

    希望这会有所帮助!

    【讨论】:

    • 我已经实现了这个方法groupCreated并添加了参与者,但问题是当我向群组发送消息时,群组的成员没有收到消息,以简单的方式告知当来自群组时,该聊天不会在其他成员中打开。
    • 在您的SendMessage SignalR 方法中,您已经完成了以下操作:var sender = AllConnectedParticipants.Find(x =&gt; x.Participant.Id == message.FromId); 该组不是已知的参与者,因此不会发送任何消息。调用groupCreated 后,您需要立即加入新组的房间。用户是 ng-chat 的参与者,组也是如此。在 ng-chat 中,当消息在组中发送时,它会发送到组(而不是每个单独的用户),这意味着您的 Participant.Id 将是 ng-chat 在调用 groupCreated 时生成的唯一 ID。
    • 好的。当你能做一个例子以确保我以正确的方式做这件事时,我对此很感兴趣。对不起我的英语
    • 我将更新 SignalR 演示项目以支持群组,并在更新后通知您:)
    • 谢谢,我将不胜感激
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 2018-05-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    相关资源
    最近更新 更多