I'm testing SignalR (0.4.0 via nuget) and can't find any way to have the server forcefully disconnect a client. I assume I'm missing something obvious.
My test code is below and I've tried both Close() and Timeout() in pretty much every place and combination I can think of with no success. The client continues to receive pulse messages, though I do always get 2 reconnections within the first 4-5 seconds that appear to come from return Connection.Close()
in OnReceivedAsync()
Server:
internal class SignalRServer
{
private Server server;
public SignalRServer()
{
server = new Server("http://localhost:13170/");
server.MapConnection<EchoConnection>("/echo");
server.Start();
Timer timer = new Timer(1000);
timer.Elapsed += OnTimer;
timer.Enabled = true;
}
void OnTimer(object sender, ElapsedEventArgs e)
{
IConnectionManager manager = server.DependencyResolver.GetService(typeof(IConnectionManager)) as IConnectionManager;
IConnection connection = manager.GetConnection<EchoConnection>();
connection.Broadcast("pulse");
connection.Close();
connection.Timeout();
}
}
internal class EchoConnection : PersistentConnection
{
protected override Task OnConnectedAsync(IRequest request, IEnumerable<string> groups, string connectionId)
{
Connection.Timeout();
Connection.Close();
return Connection.Broadcast(String.Format("{0} connection", connectionId));
}
protected override Task OnReconnectedAsync(IRequest request, IEnumerable<string> groups, string connectionId)
{
return Connection.Broadcast(String.Format("{0} reconnection", connectionId));
}
protected override Task OnReceivedAsync(string connectionId, string data)
{
Console.WriteLine(data);
Connection.Close();
Connection.Timeout();
Connection.Broadcast(data);
return Connection.Close();
}
}
Client:
internal class SignalRClient
{
private readonly Connection connection;
public SignalRClient()
{
connection = new Connection("http://localhost:13170/echo");
connection.Received += OnReceive;
connection.Closed += OnClosed;
connection
.Start()
.ContinueWith(t =>
{
if (!t.IsFaulted)
connection.Send("Hello");
else
Console.WriteLine(t.Exception);
});
Console.WriteLine(connection.ConnectionId);
}
void OnClosed()
{
// never called
connection.Stop();
}
void OnReceive(string data)
{
Console.WriteLine(data);
}
}
Sample Client output:
d7615b15-f80c-4bc5-b37b-223ef96fe96c connection
Hello
pulse
pulse
d7615b15-f80c-4bc5-b37b-223ef96fe96c reconnection
pulse
pulse
d7615b15-f80c-4bc5-b37b-223ef96fe96c reconnection
pulse
pulse
pulse
pulse
pulse
pulse
...
Send a specific string to the client to force the disconnect:
void OnReceive(string data)
{
if(data.Equals("exit"))
{
connection.Stop();
return;
}
Console.WriteLine(data);
}
In .Net Core use
Context.Abort();
https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.signalr.hubcallercontext.abort
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With