DEV Community

John Peters
John Peters

Posted on • Updated on

SignalR : Invoking Server Methods (non-proxy)

Client Side Without Proxy

This series up to now has not discussed the Client Side Hub Proxy as we are just becoming familiar with SinglarR. We'll discuss the Client Side with a proxy after this section.

The interface for a HubConnection to Invoke a server side method is:

invoke<T = any>(methodName: string, ...args: any[]): Promise<T>;
Enter fullscreen mode Exit fullscreen mode

But what does this part mean?

...args: any[]
Enter fullscreen mode Exit fullscreen mode

Here's what it doesn't mean

this.connection.invoke("SendMessage", ["p1", "p1"]);
// rather
this.connection.invoke("SendMessage", "p1", "p2");
Enter fullscreen mode Exit fullscreen mode

The number of parms must match the server side. Which is most likely why the interface allows for strongly typed objects. We were not using strong types when we discovered this.

Server Side Implied Methods

This code, on the server side, implies that the clients need to hook up to the Receive message event handler. There doesn't seem to be any contracts (if not using classes or interfaces) so don't forget to look into the Hub code for their "implied methods"

public Task SendMessage(string user, string message)
{
// Clients must have an eventhandler for ReceiveMessage
 return Clients.All.SendAsync("ReceiveMessage", user, message);
}
Enter fullscreen mode Exit fullscreen mode

Here's what the Client Side Event Handlers look like

  // Yes we hook up to the implied message method this way.
  this.connection.on("ReceiveMessage", (msg, msg2) => {
      let now = Date.now();
      let time = new Date(now).toLocaleTimeString();
      this.messages.unshift(`${time}  |  ${msg}  : ${msg2}`);
      this.stringified = this.messages.reduce((acc, item) => {
        return acc + "\n" + item;
      });   
    });
Enter fullscreen mode Exit fullscreen mode

Client Side With Proxy
Generated Proxies

In short, Proxies allow you to see the server side Hub's methods, you don't have any magic string stuff going on as shown above.

Recommendations:

✔️ Use strong types, its just is easier.
✔️ Use proxies for automatic server-side API discovery.
✔️ Store messages in an Array then convert to strings for display.
✔️ Filters and sorting work great on JavaScript arrays.

Top comments (0)