Start connection on SignalR

1

I'm creating a simple application for the purposes of studying SignalR with C # in VS2015.

How do I start the connection without having to define a method on the client? I'm doing it this way:

$.connection.hub.url = "http://localhost:8080/signalr";

var chat = $.connection.myHub;

chat.client.métodoSemUtilidade= function () {return false};

$.connection.hub.start();
    
asked by anonymous 15.09.2015 / 17:43

3 answers

1

According to the link

  

Note: Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler (s) before calling the start method. One reason for this is that there are many Hubs in an application, but you would not want to trigger the OnConnected event on every Hub if you are only going to use one of them. When the connection is established, the presence of a client method on a Hub's proxy is what it tells SignalR to trigger the OnConnected event. If you do not register any event handlers before calling the start method, you will be able to invoke methods on the Hub, but the Hub's OnConnected method will not be called and in the client methods will be invoked from the server. >

The OnConnected method is not triggered but I can still call a method on the server. What meets my need.

    
15.09.2015 / 22:03
1

I did not have to do any of this. An example:

<script type="text/javascript">

    $(function () {
        // Inicializo a conexão.
        var realtimeNotifier = $.connection.realtimeNotifierHub;

        // Trato as mensagens mandadas pelo Hub aqui.
        realtimeNotifier.client.sendMessage = function (message) {
            showOrUpdateSuccessMessage(message, false);
        };

        // Ao iniciar o Hub e, ao clicar no botão, inicio meu mecanismo,
        // que no caso é o de notificações.
        $.connection.hub.start().done(function () {
            $('#mybutton').click(function () {
                realtimeNotifier.server.doLongOperation();
            });
        });
    });
</script>

This is my Hub :

using Microsoft.AspNet.SignalR; using System.Threading;

namespace MeuProjeto.Infrastructure.Hubs
{
    public class RealtimeNotifierHub : Hub
    {
        public int recordsToBeProcessed = 100000;

        public void DoLongOperation()
        {
            for (int record = 0; record <= recordsToBeProcessed; record++)
            {
                if (ShouldNotifyClient(record))
                {
                    Clients.Caller.sendMessage(string.Format
                    ("Processing item {0} of {1}", record, recordsToBeProcessed));
                    Thread.Sleep(10);
                }
            }
        }

        private static bool ShouldNotifyClient(int record)
        {
            return record % 10 == 0;
        }
    }
}

And this is my Callback :

<script type="text/javascript">
    var n;
    function showOrUpdateSuccessMessage(message, timeout) {
        if (n == null) {
            n = noty({ text: message, type: 'success', timeout: timeout, maxVisible: 1 });
        }
        else {
            n.setText(message);
        }
    }
</script>
    
15.09.2015 / 19:12
0

The following is my script that I use so that in my intranet the quantity is displayed 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;
    }

}
}

Startup.cs file

 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>
    
26.10.2015 / 14:25