TWSocket.OnSessionClosed
Jump to navigation
Jump to search
This event is fired when the connection is closed or lost/broken.
This is the place you may initiate a TimeSetEvent TIME_ONESHOT that could attempt to reconnect some seconds later in case of Error<>0
If session is properly closed server side for some minutes, they Server may send a "please reconnect in xxx minutes" or "closed because of maintenance until xx:yy" just before before closing session so the Client may try reconnect a few minutes later or display a clean message.
// Sample of TimeSetEvent CallBack procedure
procedure TimeCallBackReconnect(TimerID, Msg:Uint; dwUser, dw1, dw2: DWord); pascal; begin PostThreadMessage(ThreadConnector.ThreadID,WM_CONNECT2SERVER,0,0); end;
// Sample of SessionClosed event
procedure TMyThread.WSocket2ServerSessionClosed(Sender: TObject; ErrCode: Word); begin if (Errcode<>0) // Set to true or false as needed and (WSocket2Server.RetryConnect=true) // Max attempts, think to reset to 0 once connected again and (WSocket2Server.RetryCount<WSocket2Server.MaxRetry) then if TimeSetEvent(WSocket2Server.RetryDelay,100,@TimeCallBackReconnect,0,TIME_ONESHOT)=0 then LogConnector('TimeSetEvent creation Error'); end else begin // You may try some reconnect also if clean close and server told // it is off for some minutes. // Server may also have informed you to reconnect somewhere else // during maintenance end;
// Sample of WM_CONNECT2SERVER event
WM_CONNECT2SERVER: begin try if WSocket2Server.State <> wsClosed then WSocket2Server.close; inc(WSocket2Server.RetryCount); WSocket2Server.Port:=StringListConfigFile.Values['ServerPort']; WSocket2Server.Addr:=StringListConfigFile.Values['ServerAddr']; WSocket2Server.Connect; except // Yes you may have an error with no SessionClosed // For example if a local firewall is blocking socket on E: Exception do begin LogConnector(E.Message); if TimeSetEvent(WSocket2Server.RetryDelay,100,@TimeCallBackReconnect,0,TIME_ONESHOT)=0 then LogConnector('TimeSetEvent creation error'); // WSocket2Server.RetryDelay may be altered if Server // sent some 'server will be off for xxx minutes' // just before a clean close end; end; end;