简体   繁体   English

是否可以使用 SignalR 向特定用户发送消息?

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

I am new to SignalR, recently I am examining and learning how the following code works.我是 SignalR 的新手,最近我正在研究和学习以下代码的工作原理。

Link: https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/tutorial-getting-started-with-signalr链接: 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.我只需要想法,因为我不知道 SignalR 提供的所有功能和方法。

In my web application users have a unique username and I need to use that data for the connection.在我的 web 应用程序中,用户有一个唯一的用户名,我需要使用该数据进行连接。 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谢谢

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添加到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然后当连接开始时,我将调用 getConnectionId 来获取服务器中的用户连接 ID 并存储到 session 存储中,因为当我们刷新浏览器时 signalR 服务器会给你新的连接 ID

Next when I click on the button I will invoke Send method in the server and I will listen on “ReceiveMessage”接下来,当我单击按钮时,我将在服务器中调用 Send 方法,并监听“ReceiveMessage”

using connection.on(“ReceiveMessage”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM