SignalR Console应用程序示例


84

是否有一个使用signalR将消息发送到.net集线器的控制台或Winform应用程序的小示例?我尝试了.net示例,并查看了Wiki,但对我而言,集线器(.net)和客户端(控制台应用程序)之间的关系没有任何意义(找不到此类示例)。该应用程序是否仅需要连接集线器的地址和名称?

是否有人可以提供一小段代码来显示应用程序连接到集线器并发送“ Hello World”或.net集线器收到的内容?

PS。我有一个标准的中心聊天示例,该示例很好用,如果我尝试在Cs中为其指定中心名称,它将停止工作,即[HubName(“ test”)],您知道原因吗?

谢谢。

当前控制台应用程序代码。

static void Main(string[] args)
{
    //Set connection
    var connection = new HubConnection("http://localhost:41627/");
    //Make proxy to hub based on hub name on server
    var myHub = connection.CreateProxy("chat");
    //Start connection
    connection.Start().ContinueWith(task =>
    {
        if (task.IsFaulted)
        {
            Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
        }
        else
        {
            Console.WriteLine("Connected");
        }
    }).Wait();

    //connection.StateChanged += connection_StateChanged;

    myHub.Invoke("Send", "HELLO World ").ContinueWith(task => {
        if(task.IsFaulted)
        {
            Console.WriteLine("There was an error calling send: {0}",task.Exception.GetBaseException());
        }
        else
        {
            Console.WriteLine("Send Complete.");
        }
    });
 }

集线器服务器。(不同的项目工作区)

public class Chat : Hub
{
    public void Send(string message)
    {
        // Call the addMessage method on all clients
        Clients.addMessage(message);
    }
}

对此的信息Wiki是http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client


好吧,实际上这确实有效,只是以为我得到的结果只是添加了一些停止点和Console.ReadLine();。在最后。哎呀!
user685590 2012年

Answers:


111

首先,您应该通过nuget在服务器应用程序上安装SignalR.Host.Self,在客户端应用程序上安装SignalR.Client:

PM>安装包SignalR.Hosting.Self-版本0.5.2

PM>安装包Microsoft.AspNet.SignalR.Client

然后将以下代码添加到您的项目中;)

(以管理员身份运行项目)

服务器控制台应用程序:

using System;
using SignalR.Hubs;

namespace SignalR.Hosting.Self.Samples {
    class Program {
        static void Main(string[] args) {
            string url = "http://127.0.0.1:8088/";
            var server = new Server(url);

            // Map the default hub url (/signalr)
            server.MapHubs();

            // Start the server
            server.Start();

            Console.WriteLine("Server running on {0}", url);

            // Keep going until somebody hits 'x'
            while (true) {
                ConsoleKeyInfo ki = Console.ReadKey(true);
                if (ki.Key == ConsoleKey.X) {
                    break;
                }
            }
        }

        [HubName("CustomHub")]
        public class MyHub : Hub {
            public string Send(string message) {
                return message;
            }

            public void DoSomething(string param) {
                Clients.addMessage(param);
            }
        }
    }
}

客户端控制台应用程序:

using System;
using SignalR.Client.Hubs;

namespace SignalRConsoleApp {
    internal class Program {
        private static void Main(string[] args) {
            //Set connection
            var connection = new HubConnection("http://127.0.0.1:8088/");
            //Make proxy to hub based on hub name on server
            var myHub = connection.CreateHubProxy("CustomHub");
            //Start connection

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error opening the connection:{0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine("Connected");
                }

            }).Wait();

            myHub.Invoke<string>("Send", "HELLO World ").ContinueWith(task => {
                if (task.IsFaulted) {
                    Console.WriteLine("There was an error calling send: {0}",
                                      task.Exception.GetBaseException());
                } else {
                    Console.WriteLine(task.Result);
                }
            });

            myHub.On<string>("addMessage", param => {
                Console.WriteLine(param);
            });

            myHub.Invoke<string>("DoSomething", "I'm doing something!!!").Wait();


            Console.Read();
            connection.Stop();
        }
    }
}

您可以在Windows应用程序中使用上面的代码,但这真的有必要吗?我不确定您的意思,您可以通过其他方式在Windows中进行通知。
巴林Mehrdad '13

1
客户端可与服务器0.5.2最多1.0.0-alpha2配合使用,例如Install-Package Microsoft.AspNet.SignalR.Client -version 1.0.0-alpha2 nuget.org/packages/Microsoft.AspNet.SignalR.Client/1.0.0-alpha2(代码和SignalR版本应该在使用VS2010 SP1的.net 4.0上兼容)一直试图弄清为什么我无法使其正常运行,最终尝试使用SignalR早期版本的客户端。
尼克·吉尔斯

很好,真的
很有帮助

4
注意,.On<T>()在调用connection.Start()方法之前,必须添加事件侦听器(方法调用)。
nicolocodev


24

SignalR 2.2.1的示例(2017年5月)

服务器

安装软件包Microsoft.AspNet.SignalR.SelfHost-版本2.2.1

[assembly: OwinStartup(typeof(Program.Startup))]
namespace ConsoleApplication116_SignalRServer
{
    class Program
    {
        static IDisposable SignalR;

        static void Main(string[] args)
        {
            string url = "http://127.0.0.1:8088";
            SignalR = WebApp.Start(url);

            Console.ReadKey();
        }

        public class Startup
        {
            public void Configuration(IAppBuilder app)
            {
                app.UseCors(CorsOptions.AllowAll);

                /*  CAMEL CASE & JSON DATE FORMATTING
                 use SignalRContractResolver from
                /programming/30005575/signalr-use-camel-case

                var settings = new JsonSerializerSettings()
                {
                    DateFormatHandling = DateFormatHandling.IsoDateFormat,
                    DateTimeZoneHandling = DateTimeZoneHandling.Utc
                };

                settings.ContractResolver = new SignalRContractResolver();
                var serializer = JsonSerializer.Create(settings);
                  
               GlobalHost.DependencyResolver.Register(typeof(JsonSerializer),  () => serializer);                
            
                 */

                app.MapSignalR();
            }
        }

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

客户

(与Mehrdad Bahrainy的回复几乎相同)

安装软件包Microsoft.AspNet.SignalR.Client-版本2.2.1

namespace ConsoleApplication116_SignalRClient
{
    class Program
    {
        private static void Main(string[] args)
        {
            var connection = new HubConnection("http://127.0.0.1:8088/");
            var myHub = connection.CreateHubProxy("MyHub");

            Console.WriteLine("Enter your name");    
            string name = Console.ReadLine();

            connection.Start().ContinueWith(task => {
                if (task.IsFaulted)
                {
                    Console.WriteLine("There was an error opening the connection:{0}", task.Exception.GetBaseException());
                }
                else
                {
                    Console.WriteLine("Connected");

                    myHub.On<string, string>("addMessage", (s1, s2) => {
                        Console.WriteLine(s1 + ": " + s2);
                    });

                    while (true)
                    {
                        Console.WriteLine("Please Enter Message");
                        string message = Console.ReadLine();

                        if (string.IsNullOrEmpty(message))
                        {
                            break;
                        }

                        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);
                            }
                        });
                    }
                }

            }).Wait();

            Console.Read();
            connection.Stop();
        }
    }
}

4
我不工作...抛出在WebApp.Start()空裁判例外
FᴀʀʜᴀɴAɴᴀᴍ

我如何在中心中看到该消息?有可能这样做吗?
Kob_24 '18

如何在dotnet核心中执行此操作:(?
Kob_24,2018年

@ Kob_24参见类MyHub,方法Send-您可以在此处看到消息。对于dotnet核心,它的工作方式几乎相同
ADOConnection '18

2
@XarisFytrakis超级简单,Ive更新了anwser,如果需要从js中使用它,则需要从此处下载合同解析器:stackoverflow.com/questions/30005575/signalr-use-camel-case以及DateFormatHandling = DateFormatHandling.IsoDateFormat。
ADOConnection '18


2

这是针对点网核心2.1的-经过大量的试验和错误,我终于可以完美地工作了:

var url = "Hub URL goes here";

var connection = new HubConnectionBuilder()
    .WithUrl($"{url}")
    .WithAutomaticReconnect() //I don't think this is totally required, but can't hurt either
    .Build();

//Start the connection
var t = connection.StartAsync();

//Wait for the connection to complete
t.Wait();

//Make your call - but in this case don't wait for a response 
//if your goal is to set it and forget it
await connection.InvokeAsync("SendMessage", "User-Server", "Message from the server");

此代码来自您典型的SignalR穷人的聊天客户端。我和其他很多人遇到的问题是在尝试向集线器发送消息之前建立连接。这很关键,因此等待异步任务完成很重要-这意味着我们通过等待任务完成来使其同步。


您实际上可以链接开始并等待连接
。StartAsync.Wait
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.