Start connection to Signalr

Asked

Viewed 490 times

1

I am creating a simple application for C# Signalr studies on VS2015.

How do I start the connection without having to define a method in 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();
  • In fact it has utility. You use it precisely to bring the information to the components of your screen.

  • Hello Gypsy. On this screen, the server will not send any information to the client. I just want to start the connection.

4 answers

1

I didn’t have to do any of that. 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 mine 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>
  • What happens if you comment on the realtimeNotifier.client.sendMessage... line? The server’s onConnect method runs?

  • Yes, normal. I just don’t intercept the message.

  • In mine it does not work without the method line. My question is just that. It seems that I am obliged to create a method in the client even if I will not use.

  • But this is strange, do you agree? What is the point of using Signalr if you will not send any response to the client?

  • Maybe I want to create a Dashboard that displays the amount of users on a given page X. Who accesses page X does not need to receive anything. Something similar to Google Analytics.

  • I think I found my answer on this link http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client#clientsetup

  • I’ll change the answer for you then.

Show 2 more comments

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 can be Many Hubs in an application, but you wouldn’t want to Trigger the Onconnected Event on Every Hub if you are only going to use to one of them. When the Connection is established, the presence of a client method on a Hub’s proxy is what Tells Signalr to Trigger the Onconnected Event. If you don’t 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 won’t be called and no 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.

  • In short, it will not work unless there is at least one defined method.

  • For what I need worked. As the Onconnected does not run, neither does the Ondisconnected, which makes manual control risky. Depending on the need it is necessary to create a dummy method only so that the server can control the connections.

0

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>

0

Browser other questions tagged

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