[c#] SignalR Console 앱 예

.net 허브에 메시지를 보내기 위해 signalR을 사용하는 콘솔 또는 winform 앱의 작은 예가 있습니까? .net 예제를 시도하고 위키를 보았지만 허브 (.net)와 클라이언트 (콘솔 앱) 사이의 관계가 이해가되지 않습니다 (이 예제를 찾을 수 없음). 앱에 연결할 허브의 주소와 이름 만 있으면 되나요?

누군가가 허브에 연결하고 “Hello World”또는 .net 허브가받는 것을 보내는 앱을 보여주는 작은 코드를 제공 할 수 있다면?.

추신. 잘 작동하는 표준 허브 채팅 예제가 있습니다. 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.");
        }
    });
 }

Hub 서버. (다른 프로젝트 작업 공간)

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

이에 대한 정보 위키는 http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client 입니다 .



답변

먼저 서버 애플리케이션에 SignalR.Host.Self를 설치하고 nuget을 통해 클라이언트 애플리케이션에 SignalR.Client를 설치해야합니다.

PM> Install-Package 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();
        }
    }
}


답변

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 응답과 거의 동일)

Install-Package 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();
        }
    }
}


답변

셀프 호스트는 이제 Owin을 사용합니다. 체크 아웃 http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host 설정 서버에. 위의 클라이언트 코드와 호환됩니다.


답변

이것은 dot net core 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 가난한 사람의 채팅 클라이언트에서 가져온 것입니다. 저와 다른 많은 사람들이 겪은 문제는 허브에 메시지를 보내기 전에 연결을 설정하는 것입니다. 이것은 매우 중요하므로 비동기 작업이 완료 될 때까지 기다리는 것이 중요합니다. 즉, 작업이 완료 될 때까지 대기하여 동기 작업을 수행하게됩니다.


답변