HTTP is state-less protocol (at least till HTTP 1.1), so client request a file, server sends a response to client and connection is closed (well, you can enable keep-alive and then connection is not closed immediately, but this is far beyond the purpose of this article). The use of the sessions, allows to store some information about client, this can be used during a client login for example. You can use whatever session unique ID, search in the list of sessions if already exists and if not exists, create a new session. Session can be destroyed after some time without using it or manually after client logout.
There are some properties in TsgcWebSocketHTTPServer which enables/disables sessions in server component. Let's see the most important:
Property | Description |
SessionState | This is the first property which has to be enabled in order to use Sessions. Without this property enabled, sessions won't work |
SessionTimeout |
Here you must set a value greater than zero (in milliseconds) for max time session will be active. |
AutoStartSession | Sessions can be created automatically (AutoStartSession = true) or manually (AutoStartSession = false). If Sessions are created automatically, server will use RemoteIP as unique identifier to see if there is an active session stored. |
TsgcWebSocketHTTPServer1.SessionState := True;
TsgcWebSocketHTTPServer1.SessionTimeout := 600000;
AutoStartSession := False;
In order to create a new session, we must create a new session id which is unique, you can use whatever, example: if client is authenticating, you can use user + password + remoteip as session id.
Then, we search in Session list if already exists, if not exists, we create a new one.
When a new session is create OnSessionStart event is called and when session is closed, OnSessionEnd event is raised.
procedure OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo);
var
vID: String;
oSession: TIdHTTPSession;
begin
if ARequestInfo.Document = '/' then
AResponseInfo.ServeFile(AContext, 'yourpathhere\index.html')
else
begin
// check if user is valid
if not ((ARequestInfo.AuthUsername = 'user') and (ARequestInfo.AuthPassword = 'pass')) then
AResponseInfo.AuthRealm := 'Authenticate'
else
begin
// create a new session id with authentication data
vID := ARequestInfo.AuthUsername + '_' + ARequestInfo.AuthPassword + '_' + ARequestInfo.RemoteIP;
// search session
oSession := TsgcWebSocketHTTPServer1.SessionList.GetSession(vID, ARequestInfo.RemoteIP);
// create new session if not exists
if not Assigned(oSession) then
oSession := TsgcWebSocketHTTPServer1.SessionList.CreateSession(ARequestInfo.RemoteIP, vID);
AResponseInfo.ContentText := '<html><head></head><body>Authenticated</body></html>';
AResponseInfo.ResponseNo := 200;
end;
end;
end;