[英]How can I send message to specific user with connectionId in SignalR
[英]How Can I Send Message To specific User with signalR
我的 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 並將其作為消息參數發送。
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();
});
});
希望這可以幫助...
如果您想在 SignalR 中向特定用戶發送消息,最簡單的方法是使用表單身份驗證。 您也可以將自定義會話與表單身份驗證一起使用。 在創建您的會話代碼后立即放置此代碼。
FormsAuthentication.SetAuthCookie(username.Trim(), false);
然后在 signalR 中,您可以使用此行向該用戶發送消息:
var username = Context.User.Identity.Name;
context.Clients.User(username).updateMessages(message);
編輯:
對於您的問題,將用戶名傳遞給此方法(接收者用戶名)並將消息推送給該用戶。然后您不需要提供 userForId,因為您已經擁有“var username = Context.User.Identity.Name;”的發件人用戶名。另外此方法只會推送到接收者用戶名的方法。 如果您還想向發件人發送消息,您需要使用“來電者”,並且您需要編寫一個新函數來在 javascript 中獲取來電者消息。我希望您能清楚。
public void Send(string username, string message)
{
context.Clients.Caller.updateMessagesCaller(message);
context.Clients.User(username).updateMessages(message);
}
此消息將僅包含該用戶名。我的建議是在您的整個項目中使用 FormAuthentication 實現。謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.