TsgcWebSocketHTTPServer | 会话

HTTP 是一种无状态协议,客户端请求文件,服务器发送响应,连接随即关闭。会话允许您存储关于客户端的信息,例如可在客户端登录期间使用。会话可以在一段时间不活动后销毁,也可以在客户端注销后手动销毁。

 

配置

TsgcWebSocketHTTPServer 中有一些属性用于在服务器组件中启用/禁用会话。最重要的属性有:

 

属性 描述
SessionState T这是必须启用的第一个属性,以便使用会话。如果不启用此属性,会话将无法工作

SessionTimeout

此处必须设置大于零的值(以毫秒为单位),作为会话保持活跃的最长时间。
AutoStartSession 会话可以自动创建(AutoStartSession = true)或手动创建(AutoStartSession = false)。如果自动创建会话,服务器将使用 RemoteIP 作为唯一标识符检查是否有活跃的存储会话。

 

 


TsgcWebSocketHTTPServer1.SessionState := True;
TsgcWebSocketHTTPServer1.SessionTimeout := 600000;
AutoStartSession := False;

 

创建会话

要创建新会话,必须创建一个唯一的新会话 ID。您可以使用任何值。示例:如果客户端正在验证身份,您可以使用 user + password + remoteip 作为会话 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;