2

I have a client which receives messages over SignalR. It works fine but it is more like a broadcast. I would like to be able to send messages to a specific client. Is it possible to do that using Azure functions C#? Here is my sample of negotiate function.

  [FunctionName("Negotiate")]
    public static SignalRConnectionInfo NegotiateSignalR(
      [HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequest req,
      [SignalRConnectionInfo(HubName = "notifications")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }
Rocket Singh
  • 469
  • 1
  • 10
  • 22

2 Answers2

1

You can do it like this.

[FunctionName("SendMessage")]
public static Task SendMessage(
    [HttpTrigger(AuthorizationLevel.Anonymous, "post")]object message, 
    [SignalR(HubName = "chat")]IAsyncCollector<SignalRMessage> signalRMessages)
{
    return signalRMessages.AddAsync(
        new SignalRMessage 
        {
            // the message will only be sent to this user ID
            UserId = "userId1",
            Target = "newMessage",
            Arguments = new [] { message }
        });
}

Reference:

Send to a user

Tony Ju
  • 14,891
  • 3
  • 17
  • 31
1
 [FunctionName("Negotiate")]
    public static SignalRConnectionInfo NegotiateSignalR(
      [HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req,
      [SignalRConnectionInfo(HubName = "notifications", UserId = "{headers.x-ms-signalr-userid}")] SignalRConnectionInfo connectionInfo)
    {
        return connectionInfo;
    }

I had to add one more property UserId in the SignalRConnectionInfo Binding and the FE client had to the pass the userid in the headers.

x-ms-signalr-userid:{userid}

with this change, the connection that is created b/w the client and signalr is associated with a userid and you can send msgs to a particular user.

Rocket Singh
  • 469
  • 1
  • 10
  • 22