Index.cshtml
@{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery.signalR-2.0.0.min.js"></script>
<script>
$(function () {
var connection = $.connection('/echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start().done(function () {
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
});
</script>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
startup.cs
using Microsoft.Owin;
using Owin;
using UI;
namespace UI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
MyConnection.cs
public class MyConnection : PersistentConnection
{
protected override Task OnConnected(IRequest request, string connectionId)
{
return Connection.Send(connectionId, "Welcome!");
}
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Connection.Broadcast(data);
}
}
我是signalR的新手。当我启动项目时,我得到以下错误:
http://localhost:49820/echo/negotiate?clientProtocol=1.3&_=1383403303981 404(未找到)
这是什么原因以及如何解决?我无法找到有关此问题的任何解决方案。 (.net framework 4.5和signalR 2.0)
答案 0 :(得分:5)
我目前无法调试您的代码,但我认为您应该考虑两个可能的问题。
1)您在启动集线器功能中错过了“$ .connection.hub”。当您从服务器端向客户端调用接收方法时,需要添加“connection.client.received”。它应该如下所示:
$(function () {
var connection = $.connection('/echo');
connection.client.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
$.connection.hub.start().done(function () {
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
});
2)您需要映射持久连接。我相信signalR 1.x应该是这样的:
RouteTable.Routes.MapConnection<MyConnection>("echo", "/echo");
但在SignalR 2.0中,您需要在集线器Startup类中执行以下操作。以下只是一个例子。
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<MyConnection>("/echo");
}