Reputation: 34188
here i got bit code for signalr and included.
$(function () {
// Proxy created on the fly
var chat = $.connection.chat;
// Declare a function on the chat hub so the server can invoke it
chat.addMessage = function (message) {
$('#messages').append('<li>' + message + '');
};
$("#broadcast").click(function () {
// Call the chat method on the server
chat.send($('#msg').val());
});
// Start the connection
$.connection.hub.start();
});
public class Chat : Hub
{
public void Send(string message)
{
// Call the addMessage method on all clients
Clients.addMessage(message);
}
}
just see this line Clients.addMessage(message);
addMessage() will invoke addMessage() function in client side but think suppose when i am sending data or message to specific client and if that is client is not connected any more then what will happen?
is there any provision in signalr like can we determine that client is connected before delivering data to specific client.
i want to detect a specific client is connected or not before sending data to client. if client is not connected then i will store data in db for that specific user. please help me with sample code that how to detect a specific client is connected or not? thanks
Upvotes: 2
Views: 3168
Reputation: 7462
I have a suggestion for this. Declare a static List
, in Chat
class. Use following code for OnConnect
event.
public override Task OnConnected() {
string connectionId = Context.ConnectionId;
// Store this connectionId in list -- This will be helpful for tracking list of connected clients.
return base.OnConnected();
}
And have OnDisconnect
method.
public override Task OnDisconnected() {
string connectionId = Context.ConnectionId;
// Remove this connectionId from list
// and save the message for disconnected clients.
// Maintain list of disconnected clients in a list, say ABC
return base.OnDisconnected();
}
On send
method execute for connected clients only.
public void Send(string message){
// Call the addMessage method on all clients
Clients.AllExcept(ABC.ToArray()).addMessage(message);
}
You can refer to this link
Upvotes: 1