1

我有一个小问题。在我在服务器和客户端之间建立连接之后。我会关闭客户端,然后关闭服务器,但服务器挂起并向我发送“程序已崩溃”我认为我遇到的问题是服务器无法识别客户端已断开连接,并且仍然认为客户端是积极的。这是源代码:

客户:

unit client;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ScktComp, Winsock, IdBaseComponent, IdComponent,
  IdTCPConnection, IdTCPClient;

type
  TForm1 = class(TForm)
    IdTCPClient1: TIdTCPClient;
    procedure FormCreate(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

function GetIpFromDns(HostName: string): string;
type
  tAddr = array[0..100] of PInAddr;
  pAddr = ^tAddr;
var
  I: Integer;
  WSA: TWSAData;
  PHE: PHostEnt;
  P: pAddr;
begin
  Result := HostName;
  WSAStartUp($101, WSA);
  try
    PHE := GetHostByName(pChar(HostName));
    if (PHE <> nil) then
    begin
  P := pAddr(PHE^.h_addr_list);
  I := 0;
  while (P^[i] <> nil) do
  begin
  Result := (inet_nToa(P^[i]^));
  Inc(I);
  end;
    end;
  except
  end;
  WSACleanUp;
end;





procedure TForm1.FormCreate(Sender: TObject);
begin
IdTCPClient1.Host := GetIpFromDns('example.no-ip.org');
IdTCPClient1.Port := 9000;
IdTCPClient1.Connect;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if IdTCPclient1.Connected = True then
IdTCPClient1.Disconnect
else
end;

end.

服务器:

unit server;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ScktComp, IdBaseComponent, IdComponent, IdTCPServer;

type
  TForm1 = class(TForm)
    IdTCPServer1: TIdTCPServer;
    procedure IdTCPServer1Connect(AThread: TIdPeerThread);
    procedure IdTCPServer1Disconnect(AThread: TIdPeerThread);



  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.IdTCPServer1Connect(AThread: TIdPeerThread);
begin
showmessage('client connected');
end;

procedure TForm1.IdTCPServer1Disconnect(AThread: TIdPeerThread);
begin
showmessage('client disconnected');
end;



end.

它可能看起来不像我为 indy 设置了一个监听端口,但我在对象检查器页面中做了。出于某种原因,如果我将 IdTCPServer.DefaultPort 和 Active 放在表单中创建它会引发更多错误。

我也试过 IdTCPClient1.DisconnectSocket 但那里也没有运气。

我是否需要在服务器端创建一些东西来定期检查连接?如果是这样,最好的方法是什么?

4

0 回答 0