It is possible to send a message to a specific user using SignalR?

Viewed 935

I am new to SignalR, recently I am examining and learning how the following code works.

Link: https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr

I would like to know what is the easiest way to send a message to a specific user using the code in the previous link. Has anyone had experience or tried to do the same? I just need ideas since I don't know all the functionalities and methods that SignalR offers.

In my web application users have a unique username and I need to use that data for the connection. I have seen that there is a way to create groups and send the message in that way but I do not understand completely, a very simple example would help me a lot.

Can you help me or give me some advice? Thank you

2 Answers

I'm already write a blog here

So basically you need to

First define a hub method like this

public async Task Send(string userId)
        {
            var message = $"Send message to you with user id {userId}";
            await Clients.Client(userId).SendAsync("ReceiveMessage", message);
        }

Add to startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSignalR(routes =>
            {
                routes.MapHub<ConnectionHub>("/connectionHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

Then finally

(function () {
        var connection = new signalR.HubConnectionBuilder().withUrl("/connectionHub").build();

        connection.start().then(function () {
            console.log("connected");

            connection.invoke('getConnectionId')
                .then(function (connectionId) {
                    sessionStorage.setItem('conectionId', connectionId);
                    // Send the connectionId to controller
                }).catch(err => console.error(err.toString()));;


        });

        $("#sendmessage").click(function () {
            var connectionId = sessionStorage.getItem('conectionId');
            connection.invoke("Send", connectionId);
        });

        connection.on("ReceiveMessage", function (message) {
            console.log(message);
        });

    })();

First I will need to make connection with the server using

new signalR.HubConnectionBuilder().withUrl(“/connectionHub”).build()

Then when the connection start I will invoke getConnectionId to get user connection id in the server and store into session storage because when we do refresh the browser signalR server will give you new connection id

Next when I click on the button I will invoke Send method in the server and I will listen on “ReceiveMessage”

using connection.on(“ReceiveMessage”);

Related