locked
Signalr javascript client connecting to a remote hub RRS feed

  • Question

  • User2002480327 posted

    My scenario is this:

    1. Server application A saves a assigned task to a database.The change in database is monitored by a change notification and there is a server hub running.

    2. Client side Javascript code,running along with server application B, has to connect to the remote hub. so that it receives a notification whenever App A inserts into the DB.

    Here is my server code

    I had downloaded owin.cors package.

     [assembly: OwinStartup(typeof(Global))]
     namespace Demo
      {
        public class Global : System.Web.HttpApplication
    {
        public static void Configuration(IAppBuilder app)
        {
    
    
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration
                {
                    EnableDetailedErrors=true,
    
                };
    
                map.RunSignalR(hubConfiguration);
            });
    
        }

    notificationHub.cs

    public class NotificationHub : Hub
    {
    
        public static Hashtable UserIdLookupTable = new Hashtable(20);
        public static Dictionary<string,Job> PendingNotificationTable = new 
        Dictionary<string,Job>(20);
    
        public void OnChange(string userId,string task,string description,string 
         duration)
        {
            if (UserIdLookupTable.ContainsKey(userId))
            {
    
        this.Clients.Client(UserIdLookupTable[userId].ToString()).Notify(userId, 
       task);
                UserIdLookupTable.Remove(userId);
                if (PendingNotificationTable.ContainsKey(userId))
                    PendingNotificationTable.Remove(userId);
    
            }
            else
                PendingNotificationTable.Add(userId, new Job(userId, task, 
        description, duration));
    
        }
    
        public override Task OnConnected()
        {
            string name =Context.QueryString["userId"];
            registerConnectionId(name);
    
            return base.OnConnected();
        }
    
        public void registerConnectionId(string userId)
        {
            if (UserIdLookupTable.ContainsKey(userId))
                 UserIdLookupTable[userId] =  Context.ConnectionId;
                else
                      UserIdLookupTable.Add(userId, Context.ConnectionId);
    
            if(PendingNotificationTable.ContainsKey(userId))
            {
                Job j=PendingNotificationTable[userId];
                OnChange(j.UserId, j.Description, j.EmployeeName, j.Duration);
    
            }
    
        }

    Client Side Code connecting to the remote hub

    My script includes

     <script src="~/Scripts/jquery-1.6.4.min.js"></script>
     <script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
      <script src="~/Scripts/HubConnection.js"></script>

    HubConnection.js

    function ConnectToHub()
     {
      jQuery.support.cors = true;
      $.connection.hub.url = "http://myip:56698";
       $.connection.hub.qs = { 'UserId' : '35' };
       var connection = $.hubConnection();
      var hub = connection.createHubProxy('NotificationHub');
      hub.on('Notify', function(userName, message) {
         console.log(userName + ' ' + message);
       });
       connection.logging = true;
       connection.start().done(function () {
            console.log('Now connected, connection ID=' + connection.id);
    
        })
        .fail(function (a)
        {
            console.log('Could not connect'+ a );
        });
        }

    While debugging using chrome, it comes to connection.start and does not go in to success or fail.Just leaves the script.There is no sign that it has connected to the server.

    It has to hit OnConnected on server right?

    Wondering whether i have missed something.

    The above client code is all i did on the client project (apart from installing signalr.client package.) Thats enough right?

    is there a chance a unity container which resolves controller instances in my client project can interfere here?

    Wednesday, May 31, 2017 5:02 PM

All replies

  • User1967761114 posted

    Hi wbsat,

    According to your code, your client side code looks like still using the original version, I’m not sure there still works,I suggest you could use current version.

    You could modify it like the following code.

    NotificationHub.cs

    [HubName("NotificationHub")]
    public class NotificationHub : Hub
    {
        //your statements 
        //…………
    
        public void HelloFromClient(string content)
        {
            //statements
        }
    }
    

    Script:

    <script src="@(Url.Content("~/Scripts/jquery-1.10.2.min.js"))"></script>
    <script src="@(Url.Content("~/Scripts/jquery.signalR-2.2.2.min.js"))"></script>
    <script src="@(Url.Content("~/signalr/hubs"))"></script>
    <script src="@(Url.Content("~/Scripts/HubConnection.js"))"></script>

    Javascript(hubconnection.js):

    $.support.cors = true;
    $.connection.hub.qs = { 'UserId': '35' };
    var notificationHub = $.connection.NotificationHub;
    //you could use hub.client.xxx to register client side method
    notificationHub.client.notify = function (userName, message) {
        console.log(userName + ' ' + message);
    }
    $.connection.hub.start().done(function () {
        console.log('Now connected, connection ID=' + notificationHub.connection.id);
        //invoke server method
        notificationHub.server.helloFromClient("xxx");
    });
    

    For more details about how to use javascript client in SignalR, you could refer to the following link.

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Thursday, June 1, 2017 2:39 AM
  • User2002480327 posted
    Basically its like this. Client side js, in mvc project A, connects to remote hub(server side) in mvc project B.
    There is no signalr code on server side in project A. no runsignalr or any config. Only signalr.client package
    was installed in the project.
    so this would not work right without any config? <script src="@(Url.Content("~/signalr/hubs"))"></script> 

    you think the above code is necessary when there is no hub in server side A?

    The server code above are all from project B as that is where the hub is.


    i have been following the msdn doc.




    Thursday, June 1, 2017 3:10 AM
  • User1967761114 posted

    Hi wbsat,

    According to your last reply,you could modify the part of script references like the following code.

    <script src="@(Url.Content("~/Scripts/jquery-1.10.2.min.js"))"></script>
    <script src="@(Url.Content("~/Scripts/jquery.signalR-2.2.2.min.js"))"></script>
    //it will auto generate by the SignalR server <script src="http://myip:56698/signalr/hubs"></script> <script src="@(Url.Content("~/Scripts/HubConnection.js"))"></script>

    If you have any other questions, please feel free to contact me any time.

    Best Regards

    Even

    Thursday, June 1, 2017 5:23 AM