【问题标题】:Using the new signalR for DotNet core to send messages from console App to web page使用 DotNet 核心的新 signalR 将消息从控制台应用程序发送到网页
【发布时间】:2018-02-25 10:11:34
【问题描述】:

我正在使用来自https://blogs.msdn.microsoft.com/webdev/2017/09/14/announcing-signalr-for-asp-net-core-2-0/ 的这个示例来创建一个控制台应用程序,该应用程序可以将消息从一个简单的控制台应用程序发送到一个网页。

以下是控制台应用程序的简单示例,它读取用户输入并在屏幕上打印该输入,我想将相同的用户输入也发送到网页。

static void Main(string[] args)
        {
            while (true)
            {
                Console.WriteLine("Enter input:");
                string line = Console.ReadLine();
                if (line == "exit")
                {
                    break;
                }
                sendSignalToClient(line);
                Console.Write("Message Sent To Client: " + line);
            }
        }

        private static void sendSignalToClient(string line)
        {
            //Send a message from this app to web client using signalR
        }

我刚刚开始了解这一点。任何与此相关的材料或建议表示赞赏。 -谢谢

编辑:我正在使用一个示例 signalR 聊天应用程序。

public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }

public class ChatHub : Hub
    {
        public void Send(string name, string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.All.InvokeAsync("broadcastMessage", name, message);
        }
    }

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR();
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseFileServer();

            app.UseSignalR(routes =>
            {
                routes.MapHub<ChatHub>("chat");
            });
        }

以下是向网页发送消息的控制台应用程序代码

class Program : Hub
{
    static void Main(string[] args)
    {
        Task.Run(Run).Wait();
    }

    static async Task Run()
    {
        var connection = new HubConnectionBuilder()
            .WithUrl("http://localhost:59768/chat")
            .WithConsoleLogger()
            .WithMessagePackProtocol()
            .WithTransport(TransportType.WebSockets)
            .Build();

        await connection.StartAsync();

        Console.WriteLine("Starting connection. Press Ctrl-C to close.");
        var cts = new CancellationTokenSource();
        Console.CancelKeyPress += (sender, a) =>
        {
            a.Cancel = true;
            cts.Cancel();
        };

        connection.Closed += e =>
        {
            Console.WriteLine("Connection closed with error: {0}", e);

            cts.Cancel();
            return Task.CompletedTask;
        };

        connection.On("broadcastMessage", async () =>
        {


        });

        while (true)
        {
            Thread.Sleep(2000);

            await connection.SendAsync("send", "alex", "hello");

        }
    }

所有代码都在运行,但在控制台应用程序上我收到了这个异常:

 Microsoft.AspNetCore.Sockets.Client.HttpConnection[19]
      09/17/2017 13:47:17: Connection Id 40da6d4b-9c47-4831-802f-628bbb172e10: An exception was thrown from the 'Received' event handler.
System.FormatException: Target method expects 0 arguments(s) but invocation has 2 argument(s).
   at Microsoft.AspNetCore.SignalR.Internal.Protocol.MessagePackHubProtocol.CreateInvocationMessage(Unpacker unpacker, IInvocationBinder binder)
   at Microsoft.AspNetCore.SignalR.Internal.Protocol.MessagePackHubProtocol.TryParseMessages(ReadOnlyBuffer`1 input, IInvocationBinder binder, IList`1& messages)
   at Microsoft.AspNetCore.SignalR.Internal.HubProtocolReaderWriter.ReadMessages(Byte[] input, IInvocationBinder binder, IList`1& messages)
   at Microsoft.AspNetCore.SignalR.Client.HubConnection.<OnDataReceivedAsync>d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Sockets.Client.HttpConnection.<>c__DisplayClass49_0.<<ReceiveAsync>b__0>d.MoveNext()

【问题讨论】:

    标签: asp.net-core signalr .net-core


    【解决方案1】:

    看看这个教程,虽然它有点旧,但它会给你很好的建议:

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

    一方面,您的网页需要连接到 SignalR 集线器,另一方面,您的控制台应该连接到可能在您的 Web 项目中的服务,以将消息发送到集线器并从那里发送到所有注册的客户端.关键是集线器在客户端执行 JavaScript 函数,但由于注册,它必须知道客户端,并且必须调用集线器实例才能执行方法。让我感到有意义的是将集线器注入 API 控制器,并使用 httpclient 将输入发布到您的控制器。

    另一个很好的教程,但这个是最近的:

    https://spontifixus.github.io/ASPNET-Core-SignalR-with-Aurelia-and-Webpack/

    希望对你有帮助。

    胡安

    编辑:

    我刚刚在这里找到了相同问题的答案(2017 年 5 月):

    SignalR Console app example

    在服务器端:

     [HubName("MyHub")]
            public class MyHub : Hub
            {
                public void Send(string name, string message)
                {
                    Clients.All.addMessage(name, message);
                }
            }
    

    在客户端:

     var myHub = connection.CreateHubProxy("MyHub");
    ...
    // To write received messages:
     myHub.On<string, string>("addMessage", (s1, s2) => {
                            Console.WriteLine(s1 + ": " + s2);
                        });
    ...
    // To send messages:
     myHub.Invoke<string>("Send", name, message).ContinueWith(task1 => {
                                if (task1.IsFaulted)
                                {
                                    Console.WriteLine("There was an error calling send: {0}", task1.Exception.GetBaseException());
                                }
                                else
                                {
                                    Console.WriteLine(task1.Result);
                                }
                            });
    

    这可能对你也有用,亚历山大。

    希望对你有帮助。

    胡安

    【讨论】:

    • 谢谢,我可以通过控制台应用程序发送消息,但我也遇到了异常。
    • 我会尝试帮助使用笔记本电脑,这东西只是手机就很复杂......哈哈......但是是的,根据异常消息,有些参数有问题,我真的不知道问题是客户端还是服务器端。我会在几个小时内看看它。承诺。
    • 好的,但是客户端例外。
    • 我会说 David Fowl 的回答是正确的,您在客户端的异常是因为参数不匹配,您发送两个并且方法期望一个,也许您可​​以创建一个包含这些属性的类并且只发送一个序列化的对象。
    【解决方案2】:

    您的事件处理程序应该接受一个字符串参数,它应该如下所示:

    connection.On<string>("broadcastMessage", data =>
    {
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-02
      • 1970-01-01
      • 1970-01-01
      • 2013-09-15
      • 2018-11-09
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多