是否甚至可以向连接到集线器的所有(或选定)连接的客户端发送消息?我的意思是从服务器端到所有客户端。我可以将客户端数据发送到服务器窗口,但是当我进入并尝试从服务器端发送时,客户端窗口上什么也没有发生。如何从服务器应用程序直接推送通知?
服务器:
namespace SignalRHub
{
class Program
{
static void Main(string[] args)
{
string url = @"http://localhost:8080/";
using (WebApp.Start<Startup>(url))
{
Console.WriteLine(string.Format("Server running at {0}", url));
Console.ReadLine();
while (true)
{
// get text to send
Console.WriteLine("Enter your message:");
string line = Console.ReadLine();
// Get hub context
IHubContext ctx = GlobalHost.ConnectionManager.GetHubContext<TestHub>();
// call addMessage on all clients of context
ctx.Clients.All.addMessage(line);
// pause to allow clients to receive
Console.ReadLine();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
}
[HubName("TestHub")]
public class TestHub : Hub
{
public void SendMsg(string message)
{
Console.WriteLine(message);
}
}
}
}
客户:
namespace SignalRClient
{
class Program
{
static void Main(string[] args)
{
IHubProxy _hub;
string url = @"http://localhost:8080/";
try
{
Console.WriteLine("Connecting to: " +url);
var connection = new HubConnection(url);
_hub = connection.CreateHubProxy("TestHub");
connection.Start().Wait();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("---------- Connection OK.");
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine("------------ Connection FAILED: ");
Console.WriteLine(e);
throw;
}
string line = null;
while ((line = System.Console.ReadLine()) != null)
{
_hub.Invoke("SendMsg", line).Wait();
}
Console.Read();
}
}
}