Search code examples
c#jquerysignalrsignalr-hubsignalr.client

how to make sure Client Methods are registered before hub starts (SignalR 1.0)


I am a beginner in SignalR although I had a lot of experience during a week. As far as I understand, before the Hub starts, the client methods should be registered. Otherwise, client methods such as "onConnected" or "onDisconnected" will not be fired, which is the problem I am having now. I am working on writing a chat application. I am able to connect to hub and send text messages, and other users in the room are able to receive the messages. However, the client methods are not called. Although I think I register them before the Hub starts, but the onConnected and other client methods are not fired. Here is the code:

Chat.aspx file:

$(function () {
        // Declare a proxy to reference the hub.
        var chatHub = $.connection.chatHub;
        registerClientMethods(chatHub); // <-this is where I register client methods

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

            var roomName = $('#hdn_Roomid').val();
            var userName = $('#hdn_NameSurname').val();

            $('#hdSelectedRoom').val(roomName);
            chatHub.server.joinRoom(roomName, userName);
        });

        // Start Hub
        $.connection.hub.start().done(function () {

            //this sets up the groupchat window, and load students            
            registerEvents(chatHub);

            var name = $('#hdn_NameSurname').val();
            chatHub.server.connect(name);
            var a = 0;
        });


    });

    function registerEvents(chatHub) {
        $('#btn_SendGroupChat').live("click", function () {

            var msg = $("#txt_InputGroupChat").val();
            if (msg.length > 0) {

                var userName = $('#hdn_NameSurname').val();
                var roomname = $('#hdSelectedRoom').val();

                chatHub.server.send(msg, roomname, userName);
                ..............
            }
        });
    }

    function registerClientMethods(chatHub) { // <-- These methods are never fired

        // Calls when user successfully logged in
        chatHub.client.onConnected = function (id, userName, allUsers, messages) {

            ......
        }

        // On New User Connected
        chatHub.client.onNewUserConnected = function (id, name) {
            //AddUser(chatHub, id, name);
        }

        // On User Disconnected
        chatHub.client.onUserDisconnected = function (id, userName) {

            //var userName = $('#hdn_NameSurname').val();
            var roomname = $('#hdSelectedRoom').val();

            chatHub.server.leaveRoom(roomname, userName);

            .............

        }

        chatHub.client.messageReceived = function (userName, message) {

            AddMessage(userName, message);
        }
    }

ChatHub.cs file:

public void Connect(string userName)
    {
        var id = Context.ConnectionId;

        if (ConnectedUsers.Count(x => x.ConnectionId == id) == 0)
        {
            ConnectedUsers.Add(new UserDetail { ConnectionId = id, UserName = userName });

            // send to caller
            Clients.Caller.onConnected(id, userName, ConnectedUsers, CurrentMessage);

            // send to all except caller client
            Clients.AllExcept(id).onNewUserConnected(id, userName);
        }
    }

    public void Send(string msg, string room, string userName)
    {
        Clients.Group(room).addMessage(msg, room);
        Clients.Group(room).messageReceived(userName, msg);
    }

    public void JoinRoom(string roomName, string userName)
    {
        Groups.Add(Context.ConnectionId, roomName);

        string msg = "<div class='text-muted'>" + userName + " joined the chat.</div>";
        Clients.Group(roomName).addMessage(msg, roomName);
        Clients.Group(roomName).messageReceived(userName, msg);
    }

    public void LeaveRoom(string roomName, string userName)
    {
        Groups.Remove(Context.ConnectionId, roomName);
        string msg = "<div class='text-muted'>" + userName + " quit the chat.</div>";
        Clients.Group(roomName).addMessage(msg, roomName);
        Clients.Group(roomName).messageReceived(userName, msg);
    }

    public override System.Threading.Tasks.Task OnDisconnected()
    {
        var item = ConnectedUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
        if (item != null)
        {
            ConnectedUsers.Remove(item);

            var id = Context.ConnectionId;
            Clients.All.onUserDisconnected(id, item.UserName);

        }

        return base.OnDisconnected();
    }

Solution

  • Actually, El Bruno alreaad provided a solution: http://elbruno.com/2014/07/25/signalr-error-html-client-does-not-raise-onconnected-method-on-server-hub-2/

    Here is the working code for those who has similar issue:

    var chatHub;
    
        $(window).ready(function () {
        //$(function () {
            // Declare a proxy to reference the hub.
            var chatHub = $.connection.chatHub;
    
            registerClientMethods(chatHub);
    
            chatHub.client.foo = function () { }; // **This line solved the issue
    
            // Start Hub
            $.connection.hub.start().done(function () {
    
                var roomName = $('#hdn_Roomid').val();
                var userName = $('#hdn_NameSurname').val();
    
                $('#hdSelectedRoom').val(roomName);
                chatHub.server.joinRoom(roomName, userName);
    
                //this sets up the groupchat window, and load students            
                registerEvents(chatHub);
    
                var name = $('#hdn_NameSurname').val();
                chatHub.server.connect(name);
                var a = 0;
            });
    
    
        });