Socket error 10054 connection reset by peer delphi

When I call the function IdFtp.List(myList, '', false); afterwards I have logged in and changed the ftp directory, I get a socket-error #10054 exception ("Connection reset by peer.") occesionall...

When I call the function

IdFtp.List(myList, '', false);

afterwards I have logged in and changed the ftp directory, I get a socket-error #10054 exception («Connection reset by peer.») occesionally.

When I call that function e.g. 20 times consecutively I get that exception 1 time.

That problem I have only encountered on Vista OS.

Does anybody know what the problem is or how I can avoid it?

asked Mar 28, 2012 at 13:12

markus_ja's user avatar

1

Not much you can do about this, because the disconnection is done by the FTP server.
You have a few choices:

  • Increase (or disable) the timeout settings (every FTP server has a different name for it) on your FTP Server connection settings.
  • Tell server that you are alive by sending NOOP command periodically (switching to Passive mode can also help).
  • Catch that exception and reconnect silently (This is my preferred solution because we have many FTP servers and I don’t trust the sys-admins to change the FTP server time-out settings).

Here is a screen-shot from FileZilla FTP server time-out settings:

enter image description here

Note that with the above settings, the FTP client will be disconnected after 2 min of non-activity.
setting that value to 0, will disable the time-out.

answered Mar 28, 2012 at 23:27

kobik's user avatar

kobikkobik

20.9k4 gold badges59 silver badges117 bronze badges

1

The FTP protocol uses multiple socket connections. Every time you call List(), a new socket connection is established to transfer the requested listing data. It sounds like the FTP server is not always closing the socket correctly at the end of a transfer.

answered Mar 28, 2012 at 20:24

Remy Lebeau's user avatar

Remy LebeauRemy Lebeau

536k30 gold badges444 silver badges750 bronze badges

2

In the component «IdFTP», change the following properties:

  • «Passive» = «False»
  • «TransferType» = «ftASCII»

Litty's user avatar

Litty

1,8561 gold badge16 silver badges34 bronze badges

answered Feb 17, 2016 at 19:22

Luciano Trevisan Alberti's user avatar

Содержание

  1. Socket error 10054 connection reset by peer delphi
  2. Socket error 10054 connection reset by peer delphi
  3. Socket error 10054 connection reset by peer delphi

Socket error 10054 connection reset by peer delphi

код проги такой

var
Form1: TForm1;
Http : TidHttp;
CM : TidCookieManager;
Data : TStringList;
StrPage, UserID, UserName, s, str, s1, SId, SId_asp, ss, co, co_asp, asp_ss,uid_ss, co_uid, uid : String;
i : integer;
Response: TStringStream;

procedure TForm1.Button1Click(Sender: TObject);
begin
try
idHTTP1.Get(‘http://www.russianpost.ru/rp/servise/ru/home/postuslug/trackingpo’);
IdHTTP1.Response.RawHeaders.Extract (‘Set-Cookie’, Memo1.Lines);//получаем куки
s:=Memo1.Text;
// копируем куки
Sid:=’SessionId=’;

if Pos(SId, s)=0 then begin
messagedlg(‘Ошибка: Невозможно проверить обновление! Проверьте подключение к интернету.’ ,mtError, [mbOK],0)
end else begin
ss:=copy(s,pos(‘=’,s)+1,length(s));
co:=copy(ss,0,pos(‘; path=/’,ss)-1);
Edit1.Text:=co;
end;
SId_asp:=’ASP.NET_SessionId’;
if Pos(SId_asp, s)=0 then begin
messagedlg(‘Ошибка: Невозможно проверить обновление! Проверьте подключение к интернету.’ ,mtError, [mbOK],0)
end else begin
asp_ss:=copy(s,pos(‘_SessionId=’,s) +11,length(s)); //
co_asp:=copy(asp_ss,0,pos(‘; path=/; HttpOnly’,asp_ss)-1);
Edit2.Text:=co_asp;
end;
uid:=’HttpOnly’;
if Pos(uid, s)=0 then begin
messagedlg(‘Ошибка: Невозможно проверить обновление! Проверьте подключение к интернету.’ ,mtError, [mbOK],0)
end else begin
uid_ss:=copy(s,pos(‘uid=’,s)+4,leng th(s)); //
co_uid:=copy(uid_ss,0,pos(‘; expires’,uid_ss)-1);
Edit3.Text:=co_uid;
end;

Http := TIdHTTP.Create;
Data := TStringList.Create;
Response := TStringStream.Create;
Http.AllowCookies := true;
Http.HandleRedirects := true;
HTTP.Request.Accept:=’text/html, application/xhtml+xml, */*’;
HTTP.Request.Referer:=’http://www.russianpost.ru/rp/servise/ru/home/postuslug/trackingpo’;
HTTP.Request.AcceptLanguage:=’ru-RU’;
HTTP.Request.UserAgent:=’Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)’;
HTTP.Request.ContentType:=’applicat ion/x-www-form-urlencoded’;
HTTP.Request.AcceptEncoding:=’gzip, deflate’;
HTTP.Request.Host:=’www.russianpost .ru’;
HTTP.Request.ContentLength:=325;
HTTP.Request.CustomHeaders.Text:=’C ookie: SessionId=’+Edit1.Text+’;ASP.NET_Se ssionId=’+Edit2.Text+’;uid=’+Edit3. Text;
HTTP.Request.Connection:=’Keep-Alive’;
HTTP.Request.CacheControl:=’no-cache’;
Data.Add(‘OP=’);
Data.Add(‘PATHCUR=rp/servise/ru/home/postuslug/trackingpo’);
Data.Add(‘PATHFROM=’);
Data.Add(‘WHEREONOK=’);
Data.Add(‘ASP=’);
Data.Add(‘PARENTID=’);
Data.Add(‘FORUMID=’);
Data.Add(‘NEWSID=’);
Data.Add(‘DFROM=’);
Data.Add(‘DTO=’);
Data.Add(‘CA=’);
Data.Add(‘CDAY=18’);// это число меняется я пока меняю его в ручную
Data.Add(‘CMONTH=09’);// это число меняется я пока меняю его в ручную
Data.Add(‘CYEAR=2012’);// это число меняется я пока меняю его в ручную
Data.Add(‘NAVCURPAGE=’);
Data.Add(‘SEARCHTEXT=’);
Data.Add(‘searchAdd=’);
Data.Add(‘PATHWEB=RP/INDEX/RU/Home’);
Data.Add(‘PATHPAGE=RP/INDEX/RU/Home/Search’);
Data.Add(‘search1=’);
Data.Add(‘BarCode=19112254797938‘);
Data.Add(‘searchsign=1’);
Data.Add(‘entryBarCode=’);
Http.Post(‘http://www.russianpost.ru/resp_engine.aspx?Path=rp/servise/ru/home/postuslug/trackingpo’, Data, Response);
memo2.Text:= UTF8Encode(Response.DataString);
//Memo2.Lines.Text := idHttp1.Response.RawHeaders.GetText ;
finally
Response.Free;
Data.Free;
Http.Free;
end;
end;

суть программы должно парсить отслеживание посылки на сайте Почта россии

для проверки 19112254797938 — рабочий

P.s знаю код ужасный, не надо критики. пишу как могу

Источник

Socket error 10054 connection reset by peer delphi

перестал работать idHTTP

выдает ошибку:socket Error # 10054 Connection reset by peer

раньше все работало. думал это из за делфи кровой, скомпилил на другой машине — такая же проблема. тестил на разных машинах но результат один и тот же. В чем проблема и как исправить?
P.S. На всех машинах, на которых проводились испытания, стоит XP zver

socket Error # 10054 Connection reset by peer

У меня кажется такое же было. Означает мол «Сервер разорвал с вами соединение». Попросту говоря послал вас лесом.

Попробуйте после подобной ошибки такое делать: idHTTP1.Socket.Close;

надо с www писать, тогда гугля будет отдавать страницу
http://www.google.ru/

Без www:
• запрос HEAD долго идёт
• запрос GET нормально

C www:
• запрос HEAD нормально
• запрос GET нормально

Моя программа раз в секунду «тырила» html-страницу с сайта через idHTTP1 (зачем не важно ).
Через некоторое время вместо скачивания страницы вылазало такое окно: «socket Error # 10054 Connection reset by peer».
Заметил я его не сразу: меня у компа долго не было, а после «энного» такого окна программа просто вылетает без следов (а я когда вернулся долго недоумевал — мол кто прогу закрыл в моё отсутствие?).
Стал разбираться что за зверь, выяснилось в справке:

WSAECONNRESET (10054) — Connection reset by peer.
An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket.) This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

Как я понял серверу просто надоело что я всё время «тырю» страницу и он меня послал — «Удаленный хост принудительно разорвал существующее подключение.».

Так что эта ошибка зависит не сколько от программы, сколько от сервера. Я её вот таким финтом частично «вылечил», если так можно выразиться:

Источник

Socket error 10054 connection reset by peer delphi

INDY 10.5.1 (Delphi6 sp3)

try
s:=IdHTTP.Get(Link);
except
on E: Exception do
begin
. Lines.Add(E.Message);
.
end;
end;

При отключении интернета (сети) во время работы программы выпадается ошибка:

Socket Error # 10054
Connection reset by peer.

При подключении сети, ошибка та же, ничего не считывается.

При запуске программы без сети ошибка
Socket Error # 10054,
а
Connection reset by peer. отсутствует

Как разглючить idHTTP, что-то надо написать где знак вопрос?

http.CheckForDisconnect — нет такого в idHTTP.
CheckForGracefulDisconnect — это Определяет, разъединил ли пэр изящно.(promt)

Пока GET не используется, пишет «Not Connected», раз считал, уже ничего не пишет.

Другие, кто использует GET, у Вас при переподключении интернета, тоже программа заглючивается, или Вам пофигу. )

Опять сам задаю, сам отвечаю.

Ошибку Connection reset by peer убирает процедура IdHTTP.Disconnect;

Значит, если вместо знака вопроса в программе вставить вот это, всё нормально
продолжает работать.

try
IdHTTP.Disconnect;
except
end;

или так, чтобы выполнить IdHTTP.Disconnect один раз.

try
if pos(‘Connection reset by peer’,E.Message)>0 then IdHTTP.Disconnect;
except
end;

А как это в idIRC лечится?
Прост такая же проблема.

INDY 10.5.1 (Delphi6 sp3)

try
s:=IdHTTP.Get(Link);
except
on E: Exception do
begin
. Lines.Add(E.Message);
.
end;
end;

При отключении интернета (сети) во время работы программы выпадается ошибка:

Socket Error # 10054
Connection reset by peer.

При подключении сети, ошибка та же, ничего не считывается.

При запуске программы без сети ошибка
Socket Error # 10054,
а
Connection reset by peer. отсутствует

Как разглючить idHTTP, что-то надо написать где знак вопрос?

Источник

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    Соблюдайте общие правила форума

    Пожалуйста, выделяйте текст программы тегом [сode=pas] … [/сode]. Для этого используйте кнопку [code=pas] в форме ответа или комбобокс, если нужно вставить код на языке, отличном от Дельфи/Паскаля.
    Указывайте точные версии Delphi и используемых сетевых библиотек.

    Не приветствуется поднятие старых тем. Если ваш вопрос перекликается со старой темой, то для вопроса лучше создать новую тему, а старую указать в первом сообщении с описанием взаимосвязи.


    Внимание:
    попытки открытия обсуждений реализации вредоносного ПО, включая различные интерпретации спам-ботов, наказывается предупреждением на 30 дней.
    Повторная попытка — 60 дней. Последующие попытки бан.
    Мат в разделе — бан на три месяца…


    Полезные ссылки:
    user posted image MSDN Library user posted image FAQ раздела user posted image Поиск по разделу user posted image Как правильно задавать вопросы


    Выразить свое отношение к модераторам раздела можно здесь: user posted image Krid, user posted image Rouse_

    >
    Indy 10 и Socket Error #10054
    , Как не допустить закрытие сокета?

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    08.05.09, 18:57

      Притащил проект домой, думал на выходных пару часов поковырять но появилась странная ошибка Socket Error #10054 при попытке принять (скачать) файл с FTP ресурса.

      По ошибке 10054 вот что нашел:

      WSAECONNRESET (10054)
      Connection reset by peer.
      An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket.) This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

      Проще говоря сокет закрывается по непонятным мне причинам со стороны сервера.
      Причём к моменту окончания описания этой проблемы я проверил еще раз получение файла разных размеров и все прошло без ошибок…

      Вобщем я вообще не понял почему такое случилось… И как можно этого избежать в дальнейшем?


      User32



      Сообщ.
      #2

      ,
      21.10.09, 08:24

        Для себя придумал два способа:

        1) это принудительно удерживать соединения по таймеру отправляя пустую команду NOOP
        Также работают подавляющее большинство ФТП клиентов с функцией KEEPALIVE.

        2) это собственно проверка а не закрыл ли сервер сокет без уведомления нас.

        ExpandedWrap disabled

          function IfDisconnect: Boolean;

          begin

            try

              IdFTP1.SendCmd(‘NOOP’);

              Result := True; //Есть соединение

            except

              Result := False; //Нет соединения

            end;

          end;

        Как видно все банально просто, но если кто знает другое решение то поделитесь.


        AutoBOT



        Сообщ.
        #3

        ,
        03.09.10, 21:15

          Хм… А если попробовать что-то вроде IdFTP1.Socket.Close; ?))


          arj99



          Сообщ.
          #4

          ,
          04.09.10, 05:47

            M

            AutoBOT, убедительная просьба впредь не поднимать старых тем, особенно тех, что помечены «Вопрос решен».
            Внимательно смотрите на дату последнего сообщения.

            0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

            0 пользователей:

            • Предыдущая тема
            • Delphi: Сетевое программирование
            • Следующая тема

            Рейтинг@Mail.ru

            [ Script execution time: 0,0374 ]   [ 16 queries used ]   [ Generated: 10.02.23, 02:43 GMT ]  

            Venu

            unread,

            Mar 26, 2008, 3:53:12 PM3/26/08

            to

            Hi,

            EIdSocketError Socket Error # 10054 Connection reset by peer

            I am getting this exception in only few machines of my program where I am
            using TIdHTTPServer component.

            Could anyone help me out on this ?

            Thanks

            Venu

            Remy Lebeau (TeamB)

            unread,

            Mar 26, 2008, 7:46:19 PM3/26/08

            to

            «Venu» <ve…@hotmail.com> wrote in message
            news:47ea…@newsgroups.borland.com…

            > EIdSocketError Socket Error # 10054 Connection reset by peer

            That error means the other party closed the connection ungracefully, such as
            by rebotting the machine.

            > I am getting this exception in only few machines of my program
            > where I am using TIdHTTPServer component.

            Then don’t worry about it. If a client is disconnecting while TIdHTTPServer
            is reading/writing from/to it, then TIdHTTPServer will handle the socket
            error internally for you.

            Gambit

            Venu

            unread,

            Mar 27, 2008, 6:46:46 AM3/27/08

            to

            The Server and client is in the same application, infact in the same form.

            I am still getting this error

            «Remy Lebeau (TeamB)» <no….@no.spam.com> wrote in message
            news:47ea7dde$1…@newsgroups.borland.com…

            Remy Lebeau (TeamB)

            unread,

            Mar 27, 2008, 10:03:44 AM3/27/08

            to

            news:47eb…@newsgroups.borland.com…

            > The Server and client is in the same application, infact in the same form.

            Then your OS is likely messed up. It should not be possible to get that
            particular error on the same machine.

            > I am still getting this error

            What does your actual code look like? Where are are seeing the error
            exactly — client-side or server-side? What are you doing when the error
            occurs?

            Gambit

            Venu

            unread,

            Mar 27, 2008, 11:47:08 AM3/27/08

            to

            I am following the example
            http://www.delphi3000.com/article.asp?ID=3081

            On «TfrmServer.httpServerCommandGet» I am doing the page processing.

            At one instance, I need to run an external function (which takes 5-7 secs)
            to do some database processing and
            I have to show the corresponding error page.

            During this time, it comes up with an access violation with the

            «EIdSocketError Socket Error # 10054 Connection reset by peer»

            The call trace looks like this

            :7c812a5b kernel32.RaiseException + 0x52
            IdStack.TIdStack.RaiseSockError(10054)
            IdTCPConnection.TIdTCPConnection.WriteBuffer((no value), 105,True)
            IdTCPConnection.TIdTCPConnection.FlushWriteBuffer(-1);
            IdTCPConnection.TIdTCPConnection.CloseWriteBuffer
            IdCustomHTTPServer.TIdHTTPResponseInfo.WriteHeader
            IdCustomHTTPServer.TIdCustomHTTPServer.DoExecute($21302E0)
            IdTCPServer.IdPeerThread.Run
            IdThread.TIdThread.Execute
            Classes.ThreadProc($21302E0)
            System.ThreadWrapper($2195610)
            :7c80b683 ; C:WINDOWSsystem32kernel32.dll

            news:47eb499b$1…@newsgroups.borland.com…

            Remy Lebeau (TeamB)

            unread,

            Mar 27, 2008, 1:02:53 PM3/27/08

            to

            >I am following the example
            > http://www.delphi3000.com/article.asp?ID=3081

            That article is quite old (2005).

            > On «TfrmServer.httpServerCommandGet» I am doing the page processing.

            That code is not thread-safe. And much of its logic is redundant as well,
            as it is duplicating logic that TIdHTTPServer natively implements
            internally.

            > At one instance, I need to run an external function (which takes
            > 5-7 secs) to do some database processing and I have to show
            > the corresponding error page.
            >
            > During this time, it comes up with an access violation with the
            > «EIdSocketError Socket Error # 10054 Connection reset by peer»

            The only way that error can occur is if the socket is being disconnected
            abnormally on the client side while waiting for the server’s reply. Changes
            are, the client has a timeout implemented on its end, and is not closing its
            socket endpoint properly.

            > The call trace looks like this

            You did not say which version of Indy 9 you are using. If you ave not
            already done so, make sure you are using the latest Indy 9.0.50 snapshot,
            and then see if the problem continues.

            Gambit

            Venu

            unread,

            Mar 28, 2008, 8:50:26 AM3/28/08

            to

            > The only way that error can occur is if the socket is being disconnected
            > abnormally on the client side while waiting for the server’s reply.
            > Changes are, the client has a timeout implemented on its end, and is not
            > closing its socket endpoint properly.
            >

            How to make the client socket connection to stay alive, I am using the
            webbrowser component. Any ideas ?

            Remy Lebeau (TeamB)

            unread,

            Mar 28, 2008, 11:29:18 AM3/28/08

            to

            news:47ec…@newsgroups.borland.com…

            > How to make the client socket connection to stay alive

            There is no way to force that on the server side.

            > I am using the webbrowser component.

            By default, the HTTP 1.0 protocol does not use keep-alives, unless the
            client explicitally asks for them. The HTTP 1.1 protocol, on the other
            hand, always uses keep-alives, unless the client explicitally asks not to.
            Either way, TIdHTTPServer has a KeepAlive property to support that. It is
            set to False initially, so you will have to set it to True yourself. But it
            is still up to the client to decide whether to use keep-alives or not.

            Gambit

            Venu

            unread,

            Mar 28, 2008, 11:43:44 AM3/28/08

            to

            >> How to make the client socket connection to stay alive
            >
            > There is no way to force that on the server side.

            Is there a way to force from the client side

            campo…@gmail.com

            unread,

            Aug 15, 2013, 8:16:41 PM8/15/13

            to

            Понравилась статья? Поделить с друзьями:

            Читайте также:

          • Socket error 10051 network is unreachable
          • Socket error 10038 socket operation on non socket delphi
          • Soap an error occurred when verifying security for the message
          • Socket error 10035
          • Soap 415 error

          • 0 0 голоса
            Рейтинг статьи
            Подписаться
            Уведомить о
            guest

            0 комментариев
            Старые
            Новые Популярные
            Межтекстовые Отзывы
            Посмотреть все комментарии