Reputation: 1387
I want to have a simple long pool request over HTTP
, now question is that how can I realize the request connection still is alive
public async Task<ApiResponse<DeviceLongPoolRequest.Result>> Get(DeviceLongPoolRequest model)
{
var check = Redis.Get<string>($"dev:check:{model.TokenKey}");
while (check == null && /****** HERE: Request.IsConnected ******/)
{
await Task.Delay(2000);
check = Redis.Get<string>($"dev:check:{model.TokenKey}");
}
return new ApiResponse<DeviceLongPoolRequest.Result>
{
Data = new DeviceLongPoolRequest.Result { TokenKey = check }
};
}
Upvotes: 2
Views: 118
Reputation: 143359
There's no easy way to determine if the client still has a persistent HTTP connection with the server. Hosts like ASP.NET still behaves like they have an active connection and lets you continuously write to the HTTP Response even when the client is no longer connected.
You can check for base.Response.IsClosed
to determine whether the Server has closed the connection but the only opportunity you have determine that there's no longer an active connection is if writing to the Response Stream throws an Exception where you'll definitely know there's no longer an active connection, but this is unreliable and wont throw in many situations as ASP.NET still accepts writes on lost client connections, even more so if the host is buffering responses or there's an intermediate proxy.
The only reliable way we've found is to implement heartbeats where if you don't receive a heartbeat from the client within an arbitrary period of time the server can assume the connection is no longer active and can close the connection itself.
If the max time for your long polls is only for a short time (e.g. <1 min) you can just assume the client is always connected and the Service will always execute for the full 30-60s, whether they're connected or not. For longer periods of time you shouldn't use a ServiceStack Service, register a IAppHost.RawHttpHandler
and implement custom hearbeats like ServiceStack's ServerEventsFeature does.
Upvotes: 2