登录后连接到SignalR或与SignalR延迟连接
问题描述:
我正在使用SignalR & MVC。我查找的代码实际上是在启动时将用户连接到集线器。登录后连接到SignalR或与SignalR延迟连接
[assembly: OwinStartup(typeof(Uno.Hubs.Startup))]
namespace ChatTBox
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
app.MapSignalR();
}
}
}
但是,我需要用户在成功登录后连接到SignalR,然后保持并显示已连接的登录用户列表。怎么做?
答
此调用不会将用户连接到集线器,它只是注册SignalR中间件(与调用app.UseWebApi()的方式相同)。连接用户由客户端从客户端发起。
您可以在客户端登录后连接客户端。在asp.net的例子可以被修改,以适应:
// login
// assuming your hub is called ChatTBoxHub
var chatTBoxHubProxy = $.connection.contosoChatHub;
// wire up the event the server can call on the client
chatTBoxHubProxy.client.addMessageToPage = function (name, message) {
console.log(name + ' ' + message);
};
// start the signalR connection
$.connection.hub.start().done(function() {
// Wire up Send button to call NewContosoChatMessage on the server.
});
// For .Net clients:
var hubConnection = new HubConnection("http://yourUrl/");
IHubProxy chatTBoxHubProxy = hubConnection.CreateHubProxy("ChatTBoxHub");
chatTBoxHubProxy.On<Message>("addMessageToPage", message => Console.WriteLine("Message '{0}' received from {1}", message.Body, message.Name));
await hubConnection.Start();
好我的理解,我应该创建连接并调用它在用户已成功登录门户。但是,我如何管理对单个发送者的呼叫而不是大众广播? – Salman
在服务器的集线器类中,覆盖OnConnected,OnDisconnected事件,并将静态的连接ID集合保存在适当的用户标识中。为了类似的目的,我使用了一个连接ID的静态字典给用户名。使用这种方法,您可以使用Hub中的Context.ConnectionId属性添加/删除用户,该用户可以在发送到客户端时使用连接ID:Clients.Client(connectionId).addMessageToPage(name,msg)。 – reckface