Catch the Asynchronous socket error 10061 Delphi error
How, when connecting the client, if the server is not running, to catch a system error and issue a message about server unavailability? Reread Google, but the construction is Try..Except doesn't work, and neither does Try..Except on E:Exception do. Or how to check the server availability then? The code that I used is below: (the error event works, but the system error is also issued, which is logical)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ScktComp;
type
TForm1 = class(TForm)
ClientSocket1: TClientSocket;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;
ErrorEvent: TErrorEvent; var ErrorCode: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//клик на кнопку
procedure TForm1.Button1Click(Sender: TObject);
begin
Try
ClientSocket1.Open;
Except
On E : Exception do Label1.Caption:='Ошибка подключения';
End;
end;
//при ошибке
procedure TForm1.ClientSocket1Error(Sender: TObject;
Socket:TCustomWinSocket; ErrorEvent: TErrorEvent;var ErrorCode: Integer);
begin Label1.Caption:='Ошибка';end;
end.
1 answers
You haven't completed the code for handling connection errors.
In order to suppress the exception (if you will handle the error yourself), in the OnErrorEvent
event, you must assign 0 for the ErrorCode.
Otherwise, the" insides " of TCustomWinSocket will assume that the error has not been handled and will throw an exception ESocketError
Thus, the final event handling code will look like this:
procedure TForm1.ClientSocket1Error(Sender: TObject; Socket:TCustomWinSocket; ErrorEvent: TErrorEvent;var ErrorCode: Integer);
begin
Label1.Caption:='Ошибка ' + IntToStr(ErrorCode);
ErrorCode:=0; // считаем, что ошибка обработана и подавляем исключение
// обычно рекомендуется выполнить еще и Socket.Close, т.к. сокет уже явно не работоспособен.
end;