我试图建立一个coss-domain连接。在我的JavaScript客户端中,我发现连接没有问题,但是如果我从集线器发送信号,则javascript方法不会受到影响。在控制台中没有显示错误。 JavaScript变量" chat"被定义为。我查看了互联网上的服务器教程,我大部分都复制了代码,但它没有用。
控制台应用程序主机:
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:43253/";
using (WebApp.Start(url))
{
Console.WriteLine($"Server running on {url}");
Console.ReadKey();
MyHub hub = new MyHub();
hub.Send("test", "test");
Console.ReadKey();
}
}
}
class Startup
{
public void Configuration(IAppBuilder app)
{
app.Map("/signalr", map =>
{
// Setup the cors middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration
{
};
// Run the SignalR pipeline. We're not using MapSignalR
// since this branch is already runs under the "/signalr"
// path.
map.RunSignalR(hubConfiguration);
});
}
}
public class MyHub : Hub
{
public override Task OnConnected()
{
Console.WriteLine("connected");
return base.OnConnected();
}
public void Send(string name, string message)
{
var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
context.Clients.All.addMessage(name, message);
}
}
JavaScript客户端:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="image">
</div>
<script src="~/Scripts/jquery-1.6.4.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.2.min.js"></script>
<script src="http://localhost:43253/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
$.connection.hub.url = "http://localhost:43253/signalr";
var chat = $.connection.myHub;
chat.client.addMessage = function (name, message) {
console.log(name + message);
}
});
</script>
</body>
</html>
答案 0 :(得分:0)
我修好了。问题是我忘了开始连接。刚补充:$ .connection.hub.start();在JavaScript客户端的末尾