Signalr - Messages for multiple hubs

Asked

Viewed 468 times

3

I am using Signalr in a C# web application with VS2015. This application has 2 pages A and B.

Who accesses page A connects to the "paginaA" hub and who accesses page B in the "paginaB" hub. This way I can separate the methods (client and server) of each page and make the code more organized. I don’t know if it is the best way.

In this application, page B can invoke methods for all clients from both hubs.

Paginaa Cliente

$(function () {
     $.connection.hub.url = "http://localhost:8080/signalr";

     var chat = $.connection.paginaA;

     chat.client.alert = function () {
         alert(1);
     };

     $.connection.hub.start();
});

pageA Hub

public class paginaA : Hub
{
     public void Send()
     {
          Clients.All.alert();
     }
}

Paginab Cliente

$(function () {
     $.connection.hub.url = "http://localhost:8080/signalr";

     var chat = $.connection.paginaB;

     chat.client.alert = function () {
         alert(1);
     };

     $.connection.hub.start();
});

paginaB Hub

public class paginaB : Hub
{
     public override Task OnConnected()
     {
          Clients.All.alert();
          return base.OnConnected();
     }
}

When accessing the page all should receive an alert.

Can I do that? I tried to separate the connections into 2 groups but it didn’t work.

  • 1

    How is your separation so far?

  • Read the design standards for this technology: http://www.asp.net/signalr

1 answer

2

follow my script that I use so that my Intranet displays the amount and which users are connected in real time:

My HUB Comhub.Cs:

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using Microsoft.AspNet.SignalR.Hubs;

namespace Painel.Web
{

[Serializable]
public class MessageRecipient
{
    public MessageRecipient()
    {
        chatRoomIds = new List<string>();
    }
    public string messageRecipientId { get; set; }
    public string messageRecipientName { get; set; }
    public string connectionId { get; set; }
    public string page { get; set; }
    public decimal codfil { get; set; }
    public DateTime data { get; set; }
    public string browser { get; set; }
    public List<string> chatRoomIds { get; set; }
}

[Serializable]
public class OnlineContacts
{
    public List<MessageRecipient> messageRecipients { get; set; }
    public OnlineContacts()
    {
        messageRecipients = new List<MessageRecipient>();
    }
}

public static class Usuario
{
    public static List<string> usuarios;
    public static HashSet<string> ConnectedIds = new HashSet<string>();
}


[HubName("ComHub")]
public class ComHub : Hub
{

    private static readonly ConcurrentDictionary<string, MessageRecipient> _chatUsers = new ConcurrentDictionary<string, MessageRecipient>(StringComparer.OrdinalIgnoreCase);

    public bool Connect(string userId, string userName, string codfil, string page, string browser)
    {
        try
        {
            if (string.IsNullOrEmpty(userId) | string.IsNullOrEmpty(userName))
            {
                return false;
            }
            if (GetChatUserByUserId(userId) == null)
            {
                AddUser(userId, userName, codfil, page, browser);
            }
            else
            {
                ModifyUser(userId, userName, codfil, page, browser);
            }
            SendOnlineContacts();
            return true;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Problem in connecting to chat server!");
        }
    }


    public bool enviacomando(string comando, string userId, string tipo)
    {
        if (comando != null)
        {
            MessageRecipient messageRecipient = GetChatUserByUserId(userId);
            Clients.Client(messageRecipient.connectionId).enviacomando(comando, tipo);

        }

        return true;
    }

    private bool SendOnlineContacts()
    {
        try
        {
            OnlineContacts onlineContacts = new OnlineContacts();
            foreach (var item in _chatUsers.OrderByDescending(a => a.Value.data))
            {
                onlineContacts.messageRecipients.Add(item.Value);
            }
            Clients.All.onGetOnlineContacts(onlineContacts);
            return false;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Problem in getting contacts!");
        }
    }

    private MessageRecipient ModifyUser(string userId, string userName, string codfil, string page, string browser)
    {
        var user = GetChatUserByUserId(userId);
        user.messageRecipientName = userName;
        user.connectionId = Context.ConnectionId;
        user.codfil = Convert.ToDecimal(codfil);
        user.data = DateTime.Now;
        user.page = page;
        user.browser = browser;
        _chatUsers[userId] = user;
        return user;
    }

    private MessageRecipient GetChatUserByUserId(string userId)
    {
        return _chatUsers.Values.FirstOrDefault(u => u.messageRecipientId == userId);
    }
    private MessageRecipient GetChatUserByConnectionId(string connectionId)
    {
        return _chatUsers.Values.FirstOrDefault(u => u.connectionId == connectionId);
    }


    private MessageRecipient AddUser(string userId, string userName, string codfil, string page, string browser)
    {

        var user = new MessageRecipient();
        user.messageRecipientId = userId;
        user.messageRecipientName = userName;
        user.connectionId = Context.ConnectionId;
        user.codfil = Convert.ToDecimal(codfil);
        user.data = DateTime.Now;
        user.page = page;
        user.browser = browser;
        _chatUsers[userId] = user;
        return user;
    }


    public override Task OnConnected()
    {
        Usuario.ConnectedIds.Add(Context.ConnectionId);


        Clients.All.conectados(Usuario.ConnectedIds.Count);

        return base.OnConnected();
    }


    public override Task OnDisconnected(bool stopCalled)
    {
        try
        {
            DeleteUser(Context.ConnectionId);
            return base.OnDisconnected(true);
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException("Problem in disconnecting from chat server!");
        }
    }



    private Boolean DeleteUser(string connectionId)
    {
        var returnValue = false;
        var user = GetChatUserByConnectionId(connectionId);
        if (user != null && _chatUsers.ContainsKey(user.messageRecipientId))
        {
            MessageRecipient messageRecipient;
            returnValue = _chatUsers.TryRemove(user.messageRecipientId, out messageRecipient);

            //remoave from all groups and chatrooms


        }

        return returnValue;
    }

}
}

Arquivo Startup.Cs

 using Microsoft.Owin;
 using Owin;

[assembly: OwinStartup(typeof(Painel.Web.Startup))]       
namespace Painel.Web
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();            

        }
    }
}

My HTML/Javascript:

<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="/signalr/hubs"></script>

     <script type="text/javascript">
    var Server;
    $(document).ready(function () {

           Server = $.connection.ComHub;

            $.connection.hub.start({ transport: 'auto', waitForPageLoad: true }, function () {
                Server.server.connect("<%=session.Usuario.ID_USUARIO%>", "<%=session.Usuario.CPF + " - " + session.Usuario.NOME%>", "<%=session.UsuarioFilial.FILIAL%>", window.location.toString(), getBrowser()).fail(function (e) {
                  });
              });


                 Server.client.onGetOnlineContacts = function (chatUsers) {

                  ShowTable(chatUsers, Server);
              };

});


    function ShowTable(chatUsers, Server) {


        //console.log(chatUsers.messageRecipients);

        if ($("#ListaUsuariosOnline").length) {

            var html = "<table cellspacing='0' cellpadding='5' align='Center' style='font-size:10px; width=1024px;'>";
            html += "<tr style='font-size:10px;'>";
            html += "<th style='font-size:10px;'>Usuário ID</th><th style='font-size:10px;'>Nome/CPF</th><th style='font-size:10px;'>Filial</th><th style='font-size:10px;'>Página atual</th><th style='font-size:10px;'>Navegador</th><th style='font-size:10px;'>Data/Hora</th><th style='font-size:10px;'>Ações</th>";
            html += "</tr>";

            chatUsers.messageRecipients.sort(function (a, b) {
                if (a.codfil > b.codfil) {
                    return 1;
                }
                if (a.codfil < b.codfil) {
                    return -1;
                }
                // a must be equal to b
                return 0;
            });


            $.each(chatUsers.messageRecipients, function (index, value) {

                html += "<tr>";
                html += "<td>" + $(this)[0].messageRecipientId + "</td><td>" + $(this)[0].messageRecipientName + "</td><td>" + $(this)[0].codfil + "</td><td>" + $(this)[0].page + "</td><td>" + $(this)[0].browser + "</td><td>" + $(this)[0].data + "</td><td><input type='button' value='Enviar Msg' onclick=\"Server.server.enviacomando(prompt('Enviar mensagem à " + $(this)[0].messageRecipientName + "', ''), '" + $(this)[0].messageRecipientId + "', 'msg');\" class='btn cancel'> <input type='button' class='btn cancel' value='Enviar Commando' onclick=\"Server.server.enviacomando(prompt('Enviar comando à " + $(this)[0].messageRecipientName + "', ''), '" + $(this)[0].messageRecipientId + "', 'comando');\"></td>";
                html += "</tr>";
            });

            html += "</table>";

            var len = $.map(chatUsers.messageRecipients, function (n, i) { return i; }).length;

            $("#ListaUsuariosOnlineTotal").html(len);
            $("#ListaUsuariosOnline").html(html);

        }

    }

</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.