C# SignalR 控制台应用示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11140164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SignalR Console app example
提问by user685590
Is there a small example of a console or winform app using signalR to send a message to a .net hub?. I have tried the .net examples and have looked at the wiki but it is not making sense to me the relationship between the hub(.net) and client(console app) (could not find an example of this). Does the app just need the address and name of hub to connect?.
是否有使用 signalR 向 .net 集线器发送消息的控制台或 winform 应用程序的小示例?我已经尝试了 .net 示例并查看了 wiki,但对我来说集线器(.net)和客户端(控制台应用程序)之间的关系没有意义(找不到这样的示例)。该应用程序是否只需要集线器的地址和名称即可连接?。
If someone could provide a small tidbit of code showing the app connecting to a hub and sending "Hello World" or something that the .net hub receives?.
如果有人可以提供一小段代码,显示应用程序连接到集线器并发送“Hello World”或 .net 集线器接收到的内容?。
PS. I have a standard hub chat example which works well , if I try to assign a hub name in Cs to it , it stops working i.e [HubName("test")] , do you know the reason for this?.
附注。我有一个标准的集线器聊天示例,它运行良好,如果我尝试在 Cs 中为其分配集线器名称,它会停止工作,即 [HubName("test")],你知道这是什么原因吗?
Thanks.
谢谢。
Current Console app Code.
当前控制台应用程序代码。
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 Server. (different project workspace)
集线器服务器。(不同的项目工作区)
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addMessage(message);
}
}
Info Wiki for this is http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client
信息 Wiki 是http://www.asp.net/signalr/overview/signalr-20/hubs-api/hubs-api-guide-net-client
采纳答案by Mehrdad Bahrainy
First of all, you should install SignalR.Host.Self on the server application and SignalR.Client on your client application by nuget :
首先,您应该通过 nuget 在服务器应用程序上安装 SignalR.Host.Self 并在客户端应用程序上安装 SignalR.Client :
PM> Install-Package SignalR.Hosting.Self -Version 0.5.2
PM> Install-Package Microsoft.AspNet.SignalR.Client
PM> 安装包 SignalR.Hosting.Self -Version 0.5.2
PM> 安装包 Microsoft.AspNet.SignalR.Client
Then add the following code to your projects ;)
然后将以下代码添加到您的项目中;)
(run the projects as administrator)
(以管理员身份运行项目)
Server console app:
服务器控制台应用程序:
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);
}
}
}
}
Client console app:
客户端控制台应用程序:
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();
}
}
}
回答by lvmeijer
The Self-Host now uses Owin. Checkout http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-hostto setup the server. It's compatible with the client code above.
自主机现在使用 Owin。结帐http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-signalr-20-self-host以设置服务器。它与上面的客户端代码兼容。
回答by ADOConnection
Example for SignalR 2.2.1 (May 2017)
SignalR 2.2.1 示例(2017 年 5 月)
Server
服务器
Install-Package Microsoft.AspNet.SignalR.SelfHost -Version 2.2.1
安装包 Microsoft.AspNet.SignalR.SelfHost -Version 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
https://stackoverflow.com/questions/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);
}
}
}
}
Client
客户
(almost the same as Mehrdad Bahrainy reply)
(与 Mehrdad Bahrainy 的回复几乎相同)
Install-Package Microsoft.AspNet.SignalR.Client -Version 2.2.1
安装包 Microsoft.AspNet.SignalR.Client -Version 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)
{
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();
}
}
}
回答by dyslexicanaboko
This is for dot net core 2.1 - after a lot of trial and error I finally got this to work flawlessly:
这是针对 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");
This code is from your typical SignalR poor man's chat client. The problem that I and what seems like a lot of other people have run into is establishing a connection before attempting to send a message to the hub. This is critical, so it is important to wait for the asynchronous task to complete - which means we are making it synchronous by waiting for the task to complete.
此代码来自典型的 SignalR 穷人聊天客户端。我和许多其他人似乎遇到的问题是在尝试向集线器发送消息之前建立连接。这很关键,因此等待异步任务完成很重要——这意味着我们通过等待任务完成来使其同步。

