正常关闭客户端线程

时间:2011-11-15 20:23:44

标签: delphi delphi-7

我正在对Delphi 7 Indy9轮询客户端进行故障排除。我尝试添加一个带有waitforsingleobject的TEvent以及许多其他方式来优雅地断开连接。 readln中发生错误。错误通常是'EIDConnection ...未连接'。我把手表放在上面,线程终止了。但是'while'不会重新评估条件,直到连接从服务器收到一个消息,所以它只是在readln研磨,直到它收到一个消息。所以有时它会优雅地断开连接,但大多数时候会崩溃。有没有办法做到这一点,或者我只是尝试...除了读取和继续...提前感谢

procedure TReadingThread.Execute;
begin
    while not Terminated and FConn.Connected do
    begin
        // read msg from server
        Msg := FConn.ReadLn;
        Synchronize(ReceiveLine); 
    end;
end;

2 个答案:

答案 0 :(得分:0)

我认为您需要添加一些代码来处理Disconnect事件。我和你描述的问题有类似的问题,这就是我所做的(在这个例子中,tcpServer是TIdTCPServer的一个实例):

    procedure TformRemoteControlWnd.tcpServerDisconnect(AContext: TIdContext);
    (*
    Connection is disconnected. Be careful, because this also gets called when
    the app is shutting down while a connection is active, in which case
    tcpServer may be gone already.
    *)
    begin
      if not Application.Terminated and Assigned(tcpServer) then
      begin
        sbarStatus.SimpleText := 'TCP/IP Disconnected';
        tcpServer.Tag := 0; // used to prevent rentrancy
      end;

      // shut down connection to stop thread from calling OnExecute event
      try
        AContext.Connection.Disconnect;
      except
        Sleep(0);
      end;
    end;

答案 1 :(得分:0)

我找到了答案...... Readln将无限期地等待,直到收到回车。因此,线程位于Readln,直到服务器发送消息或套接字断开(导致崩溃)。在Delphi编译器代码中,在OnDisconnect中编写了一条注释,以使用try...except来捕获错误。因此,在断开插座之前,我需要小心清理。我以为我能找到一种更清洁的近距离方法。谢谢你的帮助。

相关问题