Handling Indy10 exceptions - Socket Error #10054 Connection reset by peer

Hi there everyone,

I am using Indy10 TCP Server/Client and I'm thinking of a way to handle an exception of type socket error #10054 - connection reset by peer. This sort of error can happen accidentally for example if the client computer experiences a sudden power failure or the client program is "killed" in the Task Manager.

Server side, I have a listview that shows all connected clients. So whenever a socket error #10054 happens, the server MUST remove the client from the listview and return the client's database connection to a connection pool. That is what I've tried to do below with OnServerException. However I noticed that whenever this procedure runs, I have memory leaks. Apart from that, my server program has no memory leaks at all.

What do you think I'm doing wrong and how can I correct it?

N.B The connection pool is based on Cary Jensen's connection pool example on this same site 

{code}
procedure TfrmServer.ServerException(AContext: TIdContext; AException: Exception);
(* What to do if there is an accidental/deliberate system disconnect of a client *)
var
  Item: TListItem;
  ClientContext: TClientContext;
begin
  // Hard cast AContext to TClientContext
  ClientContext := TClientContext(AContext);
  // Logs any server exceptions to the Process Log
  if (AException is EIdSilentException) or (AException is EIdNotConnected) then begin
    Exit;
  end;

  if AException is EIdSocketError then begin
    ShowMessage('Exception for Client at IP ' + AContext.Binding.PeerIP + ' on Port ' + IntToStr(AContext.Binding.PeerPort) + '. ' + AException.Message);
    // Update the listview by removing the disconnected client from the list
    with lvuClientsList do
    begin
      Item := FindListViewItem(lvuClientsList, DateTimeToStr(ClientContext.Client.ConnectionTime), 5);
      //
      if Item <> nil then
      begin
        Item.Selected := True;
        Item.Delete;
        // Decrease the active connections and increase available connections
        if FActiveClients > 0 then
        begin
          Dec(FActiveClients);
          Inc(FAvailableConnections);
        end;
      end;
    end;
    // Return the open connection back to the pool since the client is disconnecting
    ClientConnection := nil;
  end;
end;
{code}


Thanks a lot for your assistance.

JayDee
0
Jay
11/2/2012 2:45:04 PM
embarcadero.delphi.winsock 1874 articles. 2 followers. Follow

2 Replies
1215 Views

Similar Articles

[PageSpeed] 47

Hello Jay,

> I am using Indy10 TCP Server/Client and I'm thinking of a way to
> handle an exception of type socket error #10054 - connection reset
> by peer.

There is nothing to handle.  The connection is gone, lost at the networking 
layer.  It cannot be recovered.  Let the server handle the error for you 
so it can close its end of the the socket and stop the managing thread.

> This sort of error can happen accidentally for example if the client computer
> experiences a sudden power failure or the client program is "killed" in the
> Task Manager.

Yes, but there are other ways that the error can occur.  Anything that disrupts 
the communication can trigger it.

> Server side, I have a listview that shows all connected clients. So
> whenever a socket error #10054 happens, the server MUST remove the
> client from the listview and return the client's database connection
> to a connection pool.

That kind of logic belongs in the OnDisconnect event, which is always triggered 
regardless of how the connection is closed.  Use OnConnect to initialize 
connection-specific stuff.  Use OnDisconnect to cleanup.  Use OnExecute for 
the bulk of the work.  Use OnException for error logging, not error handling.

> That is what I've tried to do below with OnServerException.

That is the wrong thing to do.

> However I noticed that whenever this procedure runs, I have memory leaks.

> What do you think I'm doing wrong and how can I correct it?

You are handling the error in the wrong place in the wrong way.  If an EIdException-derived 
exception occurs inside the OnExecute event, let it escape into the server, 
it will handle it accordingly.

Also, ShowMessage() is not thread-safe, and neither is accessing the ListView 
directly.  If you need to display a popup message, use the Win32 API MessageBox() 
function directly instead.  I generally would not suggest using popup messages 
in a server, though.  If you get multiple clients failing at the same time, 
you are going to get multiple popup messages at the same time.  And if the 
user is not around to dismiss them right away, those threads are going to 
be blocked, would could lead to other deadlocks.  If you need to update the 
UI, you must synchornize with the main thread, such as with the TIdSync or 
TIdNotify class.

Try something more like this instead:

{code}
type
  TAddClientToUI = class(TIdNotify)
  protected
    ...
    procedure DoNotify; override;
  end;

  TRemoveClientFromUI = class(TIdNotify)
  protected
    ConnectionTime: TDateTime;
    procedure DoNotify; override;
  end;

procedure TAddClientToUI.DoNotify;
begin
  // add client to frmServer.lvuClientsList as needed...

  // Increase the active connections and decrease available connections
  Inc(FActiveClients);
  Dec(FAvailableConnections);
end;

procedure TRemoveClientFromUI.DoNotify;
var
  Item: TListItem;
begin
  with frmServer.lvuClientsList do
  begin
    Item := FindListViewItem(frmServer.lvuClientsList, DateTimeToStr(ConnectionTime), 
5);
    //
    if Item <> nil then
    begin
      Item.Selected := True;
      Item.Delete;
      // Decrease the active connections and increase available connections
      if FActiveClients > 0 then
      begin
        Dec(FActiveClients);
        Inc(FAvailableConnections);
      end;
    end;
  end;
end;

procedure TfrmServer.ServerConnect(AContext: TIdContext);
var
  ClientContext: TClientContext;
begin
  // Hard cast AContext to TClientContext
  ClientContext := TClientContext(AContext);

  // Update the listview by adding the connected client to the list
  with TAddClientToUI.Create do
  begin
    ...
    Notify;
  end;

  ...
end;

procedure TfrmServer.ServerDisconnect(AContext: TIdContext);
var
  ClientContext: TClientContext;
begin
  // Hard cast AContext to TClientContext
  ClientContext := TClientContext(AContext);

  // Update the listview by removing the disconnected client from the list
  with TRemoveClientFromUI.Create do
  begin
    ConnectionTime := ClientContext.Client.ConnectionTime;
    Notify;
  end;

  // Return the open connection back to the pool since the client is disconnecting
  ClientContext.ClientConnection := nil;
end;

procedure TfrmServer.ServerException(AContext: TIdContext; AException: Exception);
var
  ClientContext: TClientContext;
begin
  // Hard cast AContext to TClientContext
  ClientContext := TClientContext(AContext);

  // Logs any server exceptions to the Process Log
  if (AException is EIdSilentException) or (AException is EIdNotConnected) 
then begin
    Exit;
  end;

  // log the Exception as needed...
end;
{code}

--
Remy Lebeau (TeamB)
0
Remy
11/2/2012 5:42:37 PM
Thanks a million Remy. I made the changes you suggested and it works perfectly - no memory leaks!

Jay Dee

Edited by: Jay Dee on Nov 3, 2012 10:02 AM
0
Jay
11/3/2012 5:02:37 PM
Reply:

Similar Artilces:

Connection reset by peer error 10054
Hello, Using Delphi XE3 I developed a Datasnap webbroker ISAPI (IIS 7.5) application which works fine as you works with it... To be more clear If I leave the app inactive and try to use it after 3/4 minutes I receive a "socket error #10054 connection reset by peer" error I'm using a session live cycle on the server and I didn't changed any session default timeout (which should be 20mins.). Is there any kind of inactivity timeout I have to set up for a longer period ? Is there a way to intercept this error to try reconnecting to the server ? Thanks, Davide Hi, ...

Using IdHTTP I get Error 10054 Connection Reset by Peer
Hi, I'm trying to get a GIF image from a website every 15 minutes. But it only works the first time. At the next attempt (after 15 minutes) I get the error message. Here is the code : procedure TForm.Timer1Timer(Sender: TObject); begin GetRadarImage; end; procedure TForm.GetRadarImage; var MS : TMemoryStream; GIf: TGIFImage; begin MS := TMemoryStream.Create; GIf := TGIFImage.Create; try IdHTTP1.get(RadarURL,MS); Ms.Seek(0,soFromBeginning); Gif.LoadFromStream(MS); Gif.SaveToFile(ExtractFilePath(ParamStr(0))+'radar.tmp'); final...

#10054 Connection reset by peer
Hi, I upgraded from Indy 10 r3830 to r4103. Now I (very) often get this #10054 exception after I disconnect. The same application using r3830 doesn't have this problem. In the status event of IdFtp: Disconnecting then Disconnected but then this exception (#100054). I found some changes in IdFtp "DisconnectNotifyPeer": - r4103: procedure TIdFTP.DisconnectNotifyPeer; begin if IOHandler.Connected then begin IOHandler.WriteLn('QUIT'); {do not localize} IOHandler.CheckForDataOnSource(100); if not IOHandler.InputBufferIsEmpty then begin ...

I/O Error Connection reset by peer
Hi everyone, I use Net::LDAP in a script that does a daily search on a large LDAP database (~80,000 entries). The expected return from the search is ~2000 entries. One run of the script threw up this error: my $mesg = $ldap->search(base=>...); $mesg->error was "I/O Error Connection reset by peer" I dont think this has anything to do with an ldap search size limit. For one thing, I expect to get a "sizelimit exceeded" error in that case and I have error-handling for that and the other thing is that I dont expect to exceed the size limit. I use...

Firemonkey
Hi, I've made a Firemonkey application in RAD Studio XE5, it's a Client-Server application (Datasnap). In Delphi it's possible to handle 'Connection reset by peer', using a TApplicationEvents for VCL. Is there a way to do the same for Firemonkey? TIA, An vzw wrote: > In Delphi it's possible to handle 'Connection reset by peer', > using a TApplicationEvents for VCL. That is the socket error message, not a window message. Onless you are referring to the OnException event, which is only triggered for uncaught exceptions. > Is th...

Datasnap "connection reset by peer" error on iOS?
Hi, i use 3 tier application on iOS. iOS client, windows server and SQL server. i use datasnap tcp/ip for client-server connection. Everything good but after program goes to background, connection broken and iOS application gives "connection reset by peer" error. How could i solve this? - is there a way detect application goes to background? - is there a way detect connection broken and reconnect without gives an error? Thanks. ...

Web Exception was unhandled by usercode, "The underlying connection was closed: An unexpected error occurred on a receive." Exception error
  I am using a web service. I got the error: Web Exception was unhandled by usercode. The underlying connection was closed: An unexpected error occurred on a receive.  Thanks,Bharathi Hi, Under my environment, I can't see the figure which you gave. And based on my research, please refer to the following link below for more information about this issue. http://forums.asp.net/t/1114812.aspx   Please feel free to let me know if I’ve misunderstood anything.Sincerely,Zong-Qing LiMicrosoft Online Community Support Please remember to click “Mark as Answer” on the post ...

Connection Reset By Peer Error With Jaguar 4.2 Web Server
We have recently upgraded from Jaguar 4.1 to Jaguar 4.2. Our current runtime environment is Windows 2000, Jaguar 4.2 build 42012 and JDK 1.4.1_01. We use the Jaguar web server as well as the Jaguar application server. The browser that our users use is Netscape. Since the upgrade to Jaguar 4.2, we experience an intermittent problem in the web server. When a JSP is to be displayed to the user, occasionally the user gets a Netscape pop-up window stating "A network error occurred while Netscape was receiving data. (Network Error: Connection reset by peer). Try connecti...

Re: 500-Connection reset by peer errors (version 5.47)
I've found that using a proxy for http and https requests eliminates this problem. This is a good workaround for me, but it might suggest that there's something LWP is missing in the way of handling socket connections that other software (Apache, Lynx, Netscape...) does. One other (somewhat unrelated) thing I found that might help someone else out is that other browsers change the method of a redirected POST to GET. This was causing me problems where I couldn't get past the login on a secure site - I kept getting redirected in a circle back to the login page. Here&...

[connect error] Interbase Connect Error
In ODBC connect test is successfully.. but in PowerBuilder 6.5 Database Profiles is displayed error message.. Error Message is SQLSTATE = 40001 [Easysoft][Interbase]Dynamic SQL Error, SQL error code = -91, feature is not supported What means this message? Now I use PowerBuilder 6.5 & Interbase 5.6... Just I choose - Profile Name - Data Source --> This is ODBC DNS..(user DNS) - User ID - Password Does it need more? ...

Delphi 2010 + TIBDatabase + connection error (how to catch error) [Edit]
Hi All Could someone help me in this case: {code} Try DataBase.Connect:=True; Except on >databaseconnectionerror< do ShowMessage('DataBase connection faild); end; {code} I do not know, how to catch (handling) IB errors in my Delphi application. Thank You very much in advance Best Regards Jacek Edited by: Jacek Fągowski on Aug 14, 2012 9:04 AM Jacek Fągowski wrote: > Hi All > > Could someone help me in this case: > {code} > Try > DataBase.Connect:=True; > Except > on >databaseconnectionerror< do > ShowMes...

Connection reset by peer
Hello, I changed from an ADSL provider to a Fiber provider. Now I get everytime the exception "Connection reset by peer" when closing the idFTP1 connection: idFTP1.Disconnect (Indy 10) I also tried idFTP1.DisconnectNotifyPeer and idFTP1.Quit, but the exception is still raised. How can I solve this problem ? Thanks, Hubert Anemaat > {quote:title=Hubert Anemaat wrote:}{quote} > Hello, > > I changed from an ADSL provider to a Fiber provider. Now I get everytime the exception "Connection reset by peer" when closing the *idFTP1* connection Is it...

error/exception handling
Is there a way to hook into an exception handler to change what it does and how it shows unhandled errors on the page. The strait forward way is to put try catch everywhere. But it looks like UA has exception handler allready so maybe it is possible to override it??? -- are79 ------------------------------------------------------------------------ On 04/15/2010 05:06 PM, are79 wrote: > > Is there a way to hook into an exception handler to change what it does > and how it shows unhandled errors on the page. > > The strait forward way is to put try...

connection reset errors
I am having a recurring error with IE4 and our web-site. We're downloading a list of 1000 records (I realize that's a lot, but our clients insist), and toward the end of the page-load, I get a message box that says: "Internet Explorer cannot open the Internet site <url> The connection with the server was reset " and the page is not completely loaded. Does anyone know what is most likely to cause this behavior? Thanks Earl Earl, How long is it taking to download? For kicks, have you tried it with Netscape? I realize that doesn't necessar...

connection error handling
Can anyone tell me if there are plans to somehow return messages or reasons for connection failures when you attempt to connect to a Sybase database. In particular I am interested in connecting to a Direct Connect service and want to know if the connection failed because (a) the server could not be reached (such as if it had crashed) or (b) the userid authentication failed. I believe that there are 2 different OpenClient error messages returned in these situations. Right now, if a connection fails, you get a "null" connection handle, but I'm not sure if there is any...

Web resources about - Handling Indy10 exceptions - Socket Error #10054 Connection reset by peer - embarcadero.delphi.winsock

Motor vehicle exception - Wikipedia, the free encyclopedia
The exception is based on the idea that there is a lower expectation of privacy in motor vehicles due to the regulations they operate. Additionally, ...

Podcast #42 – It’s The Exception That Proves The Rule
... Language and Usage , which was frustrated by the high number of certain types of questions that were coming in. Is this podcast the exception ...

RWW News: Marco Rubio Reiterates His Opposition To Rape Or Incest Exceptions - YouTube
http://www.rightwingwatch.org/content/marco-rubio-reiterates-his-opposition-rape-or-incest-exceptions Right Wing Watch reports on the extreme ...

Why Kevin Pietersen is the exception to the No Dickhead Rule
Something fascinating is going on in English cricket at the moment.

John Lomax 'gutted' for Issac Luke, but says finals no exception to rules
... missing a grand final to a 10-game suspension, but says the NRL judiciary must maintain consistency in its rulings and cannot make exceptions ...

India becomes the exception to US nuclear ban
President George Bush has agreed to share civilian nuclear technology with India, reversing decades of US policies designed to discourage countries ...

Is Richard Umbers, Bernie Brookes' replacement as Myer CEO, an exception?
Myer's CIO was recently elevated to the top job, but he's in a very small minority.

Men Need to Admit That Jian Ghomeshi Is No Exception
That men like Jian Ghomeshi are a terrible exception and if we as men simply stand up and say we are not as bad as that, or that we are not rapists ...

China, Thailand reach visa exception agreement
China, Thailand reach visa exception agreement People's Daily Online ... this at a forum on China's foreign diplomacy held in Beijing. Both ...

No exception allowed in graft crackdown: People's Daily
No exception allowed in graft crackdown: People's Daily - Ecns.cn ecns The expulsion of Ling Jihua from the Communist Party of China (CPC) ...

Resources last updated: 12/10/2015 2:39:47 AM