99

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

この情報ウィキはhttp://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-clientです

4

5 に答える 5

122

まず、サーバー アプリケーションに SignalR.Host.Self をインストールし、クライアント アプリケーションに SignalR.Client を nuget でインストールする必要があります。

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();
        }
    }
}
于 2012-08-21T16:03:30.517 に答える
9

dotnet コアに対する @dyslexicanaboko の回答に基づいて構築するために、クライアント コンソール アプリケーションを次に示します。

ヘルパー クラスを作成します。

using System;
using Microsoft.AspNetCore.SignalR.Client;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    public class SignalRConnection
    {
        public async void Start()
        {
            var url = "http://signalr-server-url/hubname";

            var connection = new HubConnectionBuilder()
                .WithUrl(url)
                .WithAutomaticReconnect()
                .Build();

            // receive a message from the hub
            connection.On<string, string>("ReceiveMessage", (user, message) => OnReceiveMessage(user, message));

            var t = connection.StartAsync();

            t.Wait();

            // send a message to the hub
            await connection.InvokeAsync("SendMessage", "ConsoleApp", "Message from the console app");
        }

        private void OnReceiveMessage(string user, string message)
        {
            Console.WriteLine($"{user}: {message}");
        }

    }
}

次に、コンソール アプリのエントリ ポイントに次のように実装します。

using System;

namespace com.stackoverflow.SignalRClientConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var signalRConnection = new SignalRConnection();
            signalRConnection.Start();

            Console.Read();
        }
    }
}
于 2020-12-13T01:08:39.557 に答える
8

セルフホストは Owin を使用するようになりました。http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-hostをチェックして、サーバーをセットアップします。上記のクライアント コードと互換性があります。

于 2013-03-25T17:14:44.777 に答える
4

これは 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 貧乏人のチャット クライアントからのものです。私と他の多くの人が遭遇したように見える問題は、メッセージをハブに送信する前に接続を確立することです。これは非常に重要なので、非同期タスクが完了するまで待つことが重要です。つまり、タスクが完了するのを待つことでタスクを同期化します。

于 2019-10-25T03:47:30.817 に答える