0
votes

I am using SignalR for pushing messages from an ASP.NET MVC server to web clients.

I want to store the connection Id of the current client when a new connection from a client has been accepted, so that when I want to send data to this specific client, I can retrieve its connection Id from the Session and send it the message.

However, in the OnConnected event handler, the session is null. As a result, my code throws a null reference exception when I try to put the connectionId in the session.

Here's the code snippet.

using Microsoft.AspNet.SignalR;

namespace TestSignalR
{
    public class SignalRServerListener : PersistentConnection
    {
        protected override System.Threading.Tasks.Task OnConnected(
                                          IRequest request, 
                                          string connectionId)
        {
            System.Diagnostics.Debugger.Break();

            System.Diagnostics.Debug.
             Print("Connection request received and accepted from 
             client with connection Id {0}", connectionId);

            HttpContext.Current.Session["connectionId"] = connectionId;

            return base.OnConnected(request, connectionId);
        }
    }
}
1

1 Answers

1
votes

You can track the clients like below

class MyConnections
{
    private static List<String> _MyClients = new List<String>();

    public override Task OnConnected()
    {
        _MyClients.Add(Context.ConnectionId);
        return base.OnConnected();
    }

    public override Task OnDisconnected()
    {
        _MyClients.Remove(Context.ConnectionId);
        return base.OnDisconnected();
    }

    public static bool IsConnected(string cid)
    {
        return _MyClients.Contains(cid);
    }
}

Now, when the server wants to send data to one of those clients, how should the server know which connection Id should be used in the Context.Connection.Send(connectionId, message)?

Context.DefaultSignal