I implemented SignalR to my project. But I have problem sending private message. I am sending 'toConnectionID' from page.
ChatHub.cs
public void LoadPrivateMessages(string toUserName,string toConnectionID)
{
var chatHub = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
string fromUserName = Context.QueryString["userName"].ToString();
string fromConnectionID = Context.ConnectionId;
List<ChatMessageDetail> currentMessages = cachePrivateMessages.Where(x => x.ToUserName == toUserName && x.FromUserName == fromUserName && x.ToConnectionID==toConnectionID && x.FromConnectionID==fromConnectionID).ToList();
chatHub.Clients.Client(toConnectionID).privateMessagesHistory(currentMessages);
}
My currentMessages list is filling. I am OK here. But I can't take messages to page.
Javascript
chatHub.client.privateMessagesHistory = function (data) {
console.log(data);
};
My console screen is null after this JavaScript code.
Edit :
That is my connection code in document.ready function. Second is sending information about receiver.
var chatHub = $.connection.chatHub;
$.connection.hub.qs = { "userName": "@Session["userName"]" };
$.connection.hub.start().done(function () {
console.log("Connection OK !");
});
$(document).on('click','.onlineUser', function () {
var userName = $(this).attr('id');//That is which user to send(Receiver)
var toConnectionID = $(this).attr('connectionID');
chatHub.server.loadPrivateMessages(userName, toConnectionID);
$('.privateMessagediv').show();
$('.userName').html("");
$('.userName').append("<h4>" + userName + "</h4>");
$('.btnSendingPrivateMessage').attr('id', userName);
$('.btnSendingPrivateMessage').attr('connectionid', toConnectionID);
chatHub.client.privateMessagesHistory = function (data) {
$('#privateChatBox').append(data);
};
});
Edit 2 :
I solved issue.
chatHub.Clients.Client(fromConnectionID).privateMessagesHistory(currentMessages);
instead of
chatHub.Clients.Client(toConnectionID).privateMessagesHistory(currentMessages);
My original suspicion was with the toConnectionId
, but after examining your privateMessageHistory
callback registration, it's more likely a timing issue.
You need to setup the client callback before the hub .start()
.
From Microsoft:
Normally you register event handlers before calling the start method to establish the connection. If you want to register some event handlers after establishing the connection, you can do that, but you must register at least one of your event handler(s) before calling the start method
There's no need to place your callback registration in the click event.
var chatHub = $.connection.chatHub;
$.connection.hub.qs = { "userName": "@Session["userName"]" };
// callback first
chatHub.client.privateMessagesHistory = function (data) {
$('#privateChatBox').append(data);
};
// start the hub connection - note chatHub is different from your .hub
chatHub.start().done(function () {
console.log("Connection OK !");
});