Updated Edit, please see Option 3 below. All the others are relying on timeout, I posted a forced disconnect.
If you are trying a Force Disconnect -- you can get the list of the Connected Users and call the ForceLogOut Function on the server side, I saw this somewhere on code project, I hope it helps. If you only want to forceLogout/kill some of the users, just loop through and kill that connection only.
Server Side
public class User
{
public string Name { get; set; }
public HashSet<string> ConnectionIds { get; set; }
}
public class ExtendedHub : Hub
{
private static readonly ConcurrentDictionary<string, User> ActiveUsers =
new ConcurrentDictionary<string, User>(StringComparer.InvariantCultureIgnoreCase);
public IEnumerable<string> GetConnectedUsers()
{
return ActiveUsers.Where(x => {
lock (x.Value.ConnectionIds)
{
return !x.Value.ConnectionIds.Contains
(Context.ConnectionId, StringComparer.InvariantCultureIgnoreCase);
}
}).Select(x => x.Key);
}
public void forceLogOut(string to)
{
User receiver;
if (ActiveUsers.TryGetValue(to, out receiver))
{
IEnumerable<string> allReceivers;
lock (receiver.ConnectionIds)
{
allReceivers = receiver.ConnectionIds.Concat(receiver.ConnectionIds);
}
foreach (var cid in allReceivers)
{
// ***************** log out/KILL connection for whom ever your want here
Clients.Client(cid).Signout();
}
}
}
}
Client Side
// 1- Save your connection variable when you start it, and later on you can use it to stop.
var myHubProxy = $.connection.myHub
// 2- Use it when you need to stop it, IF NOT YOU WILL GET AN ERROR
myHubProxy.client.stopClient = function() {
$.connection.hub.stop();
};
// With a button for testing
$('#SomeButtonKillSignalr').click(function () {
$.connection.hub.stop();
});
Updated with Option 3: based on request... the other solutions rely on time out, but you can also force it directly by disposing the connection yourself
I opened the SignalR code up, and inside you can see DisposeAndRemoveAsync the actual termination of a client connection.
1- You can modify or call DisposeAndRemoveAsync with your connection.
2- Then call RemoveConnection(connection.ConnectionId);
public async Task DisposeAndRemoveAsync(HttpConnectionContext connection)
{
try
{
// this will force it
await connection.DisposeAsync();
}
catch (IOException ex)
{
_logger.ConnectionReset(connection.ConnectionId, ex);
}
catch (WebSocketException ex) when (ex.InnerException is IOException)
{
_logger.ConnectionReset(connection.ConnectionId, ex);
}
catch (Exception ex)
{
_logger.FailedDispose(connection.ConnectionId, ex);
}
finally
{
// Remove it from the list after disposal so that's it's easy to see
// connections that might be in a hung state via the connections list
RemoveConnection(connection.ConnectionId);
}
}
Caution, do any clean up yourself when this is done.