我对signalR有问题,我无法从集线器向特定用户发送消息。
我想这样做:
public void Send(string userToId, string userForId, string message)
{
IHubContext context = GlobalHost.ConnectionManager.GetHubContext<ChatHubs>();
//userForId - it is Session["UserId"]
context.Clients.User(userForId).updateMessages(message);
}
我已阅读本主题:http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections,但目前尚不清楚对我来说,因为我没有这个var name = Context.User.Identity.Name;
我在会话变量中具有用户信息,当我这样获得connectionId时具有用户信息:var myClientId = $.connection.hub.id;
connectionId-在刷新页面或单击项目上的另一个菜单时更改。
我有一些问题:1)我可以向没有connectionId的特定用户发送消息(仅使用session [“ UserId”])吗?2)通常,如何使用SignalR轻松进行一对一消息传递?
PS我正在使用ASP.NET MVC(C#)
您可以将广播消息发送给所有没有连接ID的用户。您只需为每个用户分配一个唯一ID,然后将其作为Message参数发送。
SignalR为每个客户端提供唯一的ID作为连接ID。您可以使用该连接ID,也可以在创建客户端时为客户端分配唯一的ID,并将其用作连接ID。多数民众赞成在您要使用什么。
编辑
只需在集线器类文件中更新您的方法即可。
public void Send(string name, string message, string connectionid)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message, connectionid);
}
并且在您的客户端中,您可以在包含SignalR文件之后更新添加代码:-
var chat = $.connection.chatHub;
chat.client.addNewMessageToPage = function (name, message, connectionid) {
if (connectionid == $('#connection').val()) {
// Do What You want Here...
};
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
$('#connection').val(prompt('Enter your ID:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val(), $('#connection').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
希望这可以帮助...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句