我今天有一个web服务器充当SignalR服务器,其中JS的连接都是进入到正确的Hub,并且处理正确。
注册和启动JS端的例子
hub = $.connection.webRTCHub;
$.connection.hub.qs = "type=pusher";
$.connection.hub.start().done(function () {
connectionId = $.connection.hub.id;
log("Connected with id ", $.connection.hub.id);
});
当我试图用C# SignalR Client Nuget-package连接到这个SignalR服务器时,我得到了连接,我得到了一个连接ID,但我不认为我连接到了正确的枢纽,因为没有触发日志,也没有正确的响应被发送到其余的客户端。
我正在使用SignalR的跟踪日志,它显示了连接,并显示ID正在连接。下面是C#客户端的连接代码
connection = new HubConnection("http://localhost/signalr/hubs/webRTCHub");
await connection.Start();
MessageBox.Show(connection.ConnectionId);
我也试过
connection = new HubConnection("http://localhost/signalr/webRTCHub");
和
connection = new HubConnection("http://localhost/");
谁能给我指出正确的方向,从哪里开始?
我看不到这里,但你需要为你要连接的Hub创建一个HubProxy。
我假设你的Hub是 "webRTCHub"。
using(var connection = new HubConnection("http://localhost/"))
{
var hubProxy = _connection.CreateHubProxy("webRTCHub");
hubProxy.On("yourevent", () =>
{
_logger.Debug("Event recieved");
});
await _connection.Start();
}
我猜你没有创建任何自定义路由来处理signalr请求。你应该初始化HubConnection对象,不需要任何url,这将初始化连接对象的url为 "signalr "作为默认值。
connection = new HubConnection("");
或只是
connection = new HubConnection();
由于你使用的是.NET FW而不是.NET Core,所以你应该在服务器上配置集线器,比如。
在你启动的时候:
public void Configuration(IAppBuilder app)
{
//Branch the pipeline here for requests that start with "/signalr"
app.Map("/signalr", map =>
{
map.UseCors(CorsOptions.AllowAll);
var hubConfiguration = new HubConfiguration { };
map.RunSignalR(hubConfiguration);
});
}
你使用的软件包:
Microsoft.AspNet.SignalR;
Microsoft.Owin;
然后在客户端对FW和Core是一样的,只要指向你的集线器。
确保你在应用启动中注册了你的集线器的路由,例如在你使用.NET core的情况下。
app.UseSignalR(routes =>
{
routes.MapHub<webRTCHubHub>("/signalr/hubs/webRTCHub");
});
当类 webRTCHub
应该是这样的。
public class webRTCHub : Hub
{
public async Task SendNotification(string userId, string message)
{
await Clients.User(userId).SendAsync("ReceiveNotification", "You have a new message: " + message);
}
public override async Task OnConnectedAsync()
{
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception exception)
{
await base.OnDisconnectedAsync(exception);
}
}
在js方面
"use strict";
var connection;
connection = new signalR.HubConnectionBuilder()
.withUrl('http://localhost/signalr/hubs/webRTCHub')
.build();
connection.on('ReceiveNotification', (message) => {
// show the message maybe
})
connection.start().catch(function (err) {
return console.error(err.toString())
});
connection.on('finished',(update)=>{
connection.stop();
});
为了从客户端向服务器发送消息,你应该在类中也创建一个方法,然后从脚本中调用该方法
更新:套餐和服务
对于 ASP.NET:
NuGet包。
Microsoft.AspNet.SignalR
绘制路线 Application_Start
RouteTable.Routes.MapHubs("/signalr/hubs/webRTCHub", new webRTCHub());
对于 .NET核心:
请确保安装以下软件包,并在其中添加SignalR。ConfigureServices
微软.AspNetCore.SignalR
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSignalR();
// ...
}