2

I'm trying to send a message using SignalR and it works if I send to everybody, but not to s specific user. I tried to use the ConnectionId that in theory should be unique, but every time I tried to use the same connectionId that I received by the client, it doesn't work.

The server-side:

public async Task SendMessage(string user, string message)
{
   var a = Context.UserIdentifier;
   await Clients.User(Context.ConnectionId).SendAsync("ReceiveMessage", user, message);
   await Clients.All.SendAsync("ReceiveMessage", user, message);
}

Trying to pass the same ConnectionId in context doesn't send the message, only when I call Clients.All

The client is an android app and I'm not sure if I should register something on my client-side.

hubConnection = HubConnectionBuilder.create("http://192.168.1.5:3000/notification").build()
    hubConnection.start()


    hubConnection.on<String, String>(
        "ReceiveMessage",
        Action2 { user: String?, message: String? ->
            requireActivity().runOnUiThread(java.lang.Runnable {
                Toast.makeText(
                    context,
                    "I'm here.",
                    Toast.LENGTH_LONG
                ).show()
            })

        },
        String::class.java,
        String::class.java
    )
Nathiel Paulino
  • 534
  • 6
  • 17
  • Have you tried using `Clients.Client(connectionId)`? Most likely `Clients.User` is not working because you are using JWT token, which may not be mapped automatically to `Context.User`. In such a case you have to manually retrieve UserId and set it to the hub's `Context` BEFORE calling your method on the server. – Pavel Sapehin Dec 30 '22 at 18:41
  • [?Related?](https://stackoverflow.com/q/19522103/6576302) – C.F.G Dec 31 '22 at 08:35

3 Answers3

0

You should use

await Clients.Client(Context.ConnectionId).SendAsync("ReceiveMessage", message);

It should works well.

Jason Pan
  • 15,263
  • 1
  • 14
  • 29
0

SignalR allows messages to be sent to a particular client connection, all connections associated with a specific user, as well as to named groups of connections. => await Clients. User(userId).

-2

if you want to send message to specific user in SignalR, easiest way is the use Form authentication. Also you can use your custom session with form authentication. Right after creation your session code put this code. FormsAuthentication.SetAuthCookie (username.Trim (), false); Then in signalR you can use this line for send message to this user: