问题
I have read through the SignalR docs and watched a few of the videos, however I can not get SignalR to host within a winforms application.
I have tried using source code off the SignalR wiki: https://github.com/SignalR/SignalR/wiki/Self-host
If you look at the "Full Sample - Hubs", what is the "server" variable? I do not understand how this works or how to convert it to C#. According to the wiki "The default SelfHost implementation is built on HttpListener and can be hosted in any kind of application (Console, Windows Service etc). "
I would like to host SignalR in C# and consume it in asp.net. Could anyone please shed some light on this for me?
回答1:
The sample in the Wiki works fine.
Please install the SignalR.Hosting.Self package using NuGet (Package Manager Console)
Install-Package SignalR.Hosting.Self
The Server lives in the SignalR.Hosting.Self namespace.
Sample
Console Application
using System;
namespace MyConsoleApplication
{
static class Program
{
static void Main(string[] args)
{
string url = "http://localhost:8081/";
var server = new SignalR.Hosting.Self.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;
}
}
}
public class MyHub : SignalR.Hubs.Hub
{
public void Send(string message)
{
Clients.addMessage(message);
}
}
}
}
Asp.NET / Javascript
<script type="text/javascript" src="Scripts/jquery-1.7.2.js"></script>
<script src="/Scripts/jquery.signalR.js" type="text/javascript"></script>
<script src="http://localhost:8081/signalr"></script>
<script type="text/javascript">
$(function () {
// create signalr hub connection
myHub= $.connection.myHub;
// start hub connection and call the send method
$.connection.hub.start(function () {
myHub.Send('Hello');
});
});
</script>
Please leave a comment if you have additional answers
回答2:
In order to make this to work for C# and ASP.NET I had to use "Cross Domain".
In the JavaScript I used:
<script type="text/javascript" src='http://localhost:8081/signalr/hubs'></script>
and added:
$.connection.hub.url = 'http://localhost:8081/signalr'
来源:https://stackoverflow.com/questions/11549902/how-to-setup-a-c-sharp-winforms-application-to-host-signalr-hubs