SignalR - How to call server function with parameter from client using hubproxy

Viewed 6359

I have my signalr running on a separate domain. We will have multiple applications using it to send and receive messages. I created the connection and hub proxy using the following code

connection = $.hubConnection("https://someurl.com", { useDefaultPath: false });
            chatHub = connection.createHubProxy('chatHub');

I can get messages from the server sent to the client using the following code which works fine

chatHub.on('receiveEntityMessage', function (chatMessage) {
                if (chatMessage) {
                    console.log(chatMessage.Message);
                }
            });

Now I dont know how to call server functions with parameters from the client. Can anybody please help me with this?

2 Answers

Since i'm not sure what is the language of your server side, i am going to provide a C# example.

C# Hub method example:

public class chatHub: Hub {

    public void YourHubMehotd(int firstParam, string secondParam){

        //The action of your method

    }

}

JS client side:

You can call your hub method like this:

{The variable with the hub connection}.server.{the method you want to call}( {the parameters} )

Example:

chatHub.server.YourHubMehotd(1,"Example");

I recomend to create a js function to call the hub method.

function callMyHubMethod(firstParam, secondParam){

    chatHub.server.YourHubMehotd(firstParam, secondParam);

}
Related