SignalR控制台应用示例

时间:2012-06-21 14:15:51

标签: c# signalr

是否有使用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.");
        }
    });
 }

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

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

Info Wiki的目的是http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client

4 个答案:

答案 0 :(得分:96)

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

  

PM>安装包SignalR.Hosting.Self -Version 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();
        }
    }
}

答案 1 :(得分:6)

自我主持人现在使用Owin。结帐http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host以设置服务器。它与上面的客户端代码兼容。

答案 2 :(得分:0)

这是针对点网核心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穷人的聊天客户端。我和其他很多人遇到的问题是在尝试向集线器发送消息之前建立连接。这很关键,因此等待异步任务完成很重要-这意味着我们通过等待任务完成来使其同步。

答案 3 :(得分:0)

要基于@dyslexicanaboko对dotnet核心的回答,请使用以下客户端控制台应用程序:

创建一个帮助器类:

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();
        }
    }
}
相关问题