我正在尝试创建一个客户端信号器应用程序。目前,我能够让我的 MVC 客户端向集线器发送消息和从集线器发送消息,但是,我的 .NET 客户端应用程序遇到了一些困难
服务器集线器代码:
namespace ServerHub
{
public class ChatterBox : Hub
{
public void Send(string message)
{
Clients.All.addMessage(message);
}
}
}
控制台 App 代码(几乎是直接从 github 提取的)
using Microsoft.AspNet.SignalR.Client.Hubs;
using ServerHub;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Say("hello from console");
}
public static void Say(string message)
{
//var connection = new HubConnection("http://localhost/");
//IHubProxy myHub = connection.CreateHubProxy("ChatterBox");
var connection = new HubConnection("http://localhost/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("ChatterBox");
//Start connection
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Success! Connected with client connection id {0}", connection.ConnectionId);
// Do more stuff here
}
});
connection.Send("Hello").ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("Send failed {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Success");
}
});
}
}
}
我在下面收到错误消息connection.Send()
必须在发送数据之前调用 Start。
我哪里做错了?
编辑:
第二次尝试:
var connection = new HubConnection("http://localhost/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("ChatterBox");
//Start connection
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Success! Connected with client connection id {0}",
connection.ConnectionId);
// Do more stuff here
connection.Send("Hello");
}
});
myHub.Invoke("Send", "lol");
仍然给我一个错误
编辑:第三次尝试
var connection = new HubConnection("http://localhost:60610/");
//Make proxy to hub based on hub name on server
var myHub = connection.CreateHubProxy("ChatterBox");
//Start connection
connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("Failed to start: {0}", task.Exception.GetBaseException());
}
else
{
//Console.WriteLine("Success! Connected with client connection id {0}", connection.ConnectionId);
myHub.Invoke("Send", "lol");
}
});
似乎在工作
我还需要设置端口号 - 例如,如果我像这样浏览我的 MVC 网站:http://localhost:60610/
,这是我需要在控制台应用程序中设置的地址。
我可以说在部署期间,它不会成为问题,因为默认情况下它将是端口 80?