HTTP는 무상태 프로토콜입니다(적어도 HTTP 1.1까지). 따라서 클라이언트가 파일을 요청하면 서버가 응답을 보내고 연결이 닫힙니다(연결이 즉시 닫히지 않도록 keep-alive를 활성화할 수 있지만 이는 이 문서의 범위를 벗어납니다). 세션을 사용하면 클라이언트에 대한 정보를 저장할 수 있으며, 예를 들어 클라이언트 로그인 중에 사용할 수 있습니다. 고유한 세션 ID를 사용하고 세션 목록을 검색하여 이미 존재하는지 확인한 다음, 없으면 새 세션을 생성할 수 있습니다. 세션은 비활성 기간 후 또는 클라이언트 로그아웃 후 수동으로 소멸될 수 있습니다.
TsgcWebSocketHTTPServer에는 서버 구성 요소에서 세션을 활성화/비활성화하는 일부 속성이 있습니다. 가장 중요한 것은 다음과 같습니다:
| 속성 | 설명 |
| SessionState | T이것은 Session을 사용하기 위해 활성화해야 하는 첫 번째 속성입니다. 이 속성을 활성화하지 않으면 세션이 작동하지 않습니다 |
|
SessionTimeout |
여기에 세션이 활성화될 최대 시간에 대해 0보다 큰 값(밀리초)을 설정해야 합니다. |
| AutoStartSession | 세션은 자동으로(AutoStartSession = true) 또는 수동으로(AutoStartSession = false) 생성할 수 있습니다. 세션이 자동으로 생성되면, 서버는 RemoteIP를 고유 식별자로 사용하여 저장된 활성 세션이 있는지 확인합니다. |
| SessionClass | Optional. The class the server uses when it creates a new session. Set it to your own TIdHTTPSession descendant to store your own data inside every session. Must be set before the server is activated. |
| SessionList | The list that holds the active sessions. Read it to search, create or remove sessions by code. You can also assign your own list if you need full control over where sessions are stored. Must be assigned before the server is activated. |
TsgcWebSocketHTTPServer1.SessionState := True;
TsgcWebSocketHTTPServer1.SessionTimeout := 600000;
TsgcWebSocketHTTPServer1.AutoStartSession := False;
새 세션을 생성하려면 고유한 새 session ID를 생성해야 합니다. 어떤 값이든 사용할 수 있습니다. 예: 클라이언트가 인증 중인 경우, user + password + remoteip를 session ID로 사용할 수 있습니다.
그런 다음 세션 목록을 검색하여 이미 존재하는지 확인하십시오. 존재하지 않으면 새로 생성하십시오.
새 세션이 생성되면 OnSessionStart 이벤트가 호출되고, 세션이 닫히면 OnSessionEnd 이벤트가 발생합니다.
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;
Once a session exists, the server attaches it to every request that carries the session cookie. Read it from ARequestInfo.Session, which is nil when the request has no session.
procedure OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo);
begin
if Assigned(ARequestInfo.Session) then
begin
// Content is a TStrings you can use to store your own values
ARequestInfo.Session.Content.Values['visits'] :=
IntToStr(StrToIntDef(ARequestInfo.Session.Content.Values['visits'], 0) + 1);
AResponseInfo.ContentText := 'Session ' + ARequestInfo.Session.SessionID +
' visits: ' + ARequestInfo.Session.Content.Values['visits'];
end
else
AResponseInfo.ContentText := 'No session';
end;
If you want to keep your own fields inside every session, instead of using the Content string list, create a descendant of TIdHTTPSession and tell the server to use it through the SessionClass property. Set it before the server is activated.
서버는 나머지 모든 작업을 계속 처리합니다. 고유한 세션 ID를 생성하고, 세션 쿠키를 전송하고, SessionTimeout을 적용하고, 오래된 세션을 제거합니다. 세션이 생성될 때 자체 필드를 초기화하려면 가상 생성자 CreateInitialized를 재정의하십시오.
type
TMySession = class(TIdHTTPSession)
private
FUserName: String;
FLoginTime: TDateTime;
public
constructor CreateInitialized(AOwner: TIdHTTPCustomSessionList;
const SessionID, RemoteIP: string); override;
property UserName: String read FUserName write FUserName;
property LoginTime: TDateTime read FLoginTime write FLoginTime;
end;
constructor TMySession.CreateInitialized(AOwner: TIdHTTPCustomSessionList;
const SessionID, RemoteIP: string);
begin
inherited CreateInitialized(AOwner, SessionID, RemoteIP);
FLoginTime := Now;
end;
// configure the server before it starts
TsgcWebSocketHTTPServer1.SessionState := True;
TsgcWebSocketHTTPServer1.SessionTimeout := 600000;
TsgcWebSocketHTTPServer1.SessionClass := TMySession;
TsgcWebSocketHTTPServer1.Active := True;
// and read it back in any request
procedure OnCommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
AResponseInfo: TIdHTTPResponseInfo);
begin
if ARequestInfo.Session is TMySession then
AResponseInfo.ContentText := TMySession(ARequestInfo.Session).UserName;
end;
If you need full control over how sessions are stored, for example keeping them in a database or sharing them between several servers, assign your own list to the SessionList property, before the server is activated. Descend from TIdHTTPDefaultSessionList and override the virtual CreateSession method. The server calls it internally from CreateUniqueSession, so the unique session ID is still generated for you.
When you assign your own SessionList, the SessionClass property no longer applies, because your list decides which class to create.
type
TMySessionList = class(TIdHTTPDefaultSessionList)
public
function CreateSession(const RemoteIP, SessionID: string)
: TIdHTTPSession; override;
end;
function TMySessionList.CreateSession(const RemoteIP, SessionID: string)
: TIdHTTPSession;
begin
Result := TMySession.CreateInitialized(Self, SessionID, RemoteIP);
SessionList.Add(Result);
end;
// assign it before the server starts
TsgcWebSocketHTTPServer1.SessionList := TMySessionList.Create(nil);
TsgcWebSocketHTTPServer1.Active := True;
The OnCreateSession event lets you return a session instance yourself, but it does not assign a session ID to it. If you create the session with a plain constructor, the session ID and the session cookie are empty and the session can never be found again on the next request. Use SessionClass instead, which is simpler and handles all of that for you.
Also, do not call SessionList.CreateUniqueSession inside OnCreateSession. That method already adds the new session to the list, and the server adds it again when your handler returns, so the same session ends up twice in the list.