簡體   English   中英

Indy 10 TCP客戶端服務器 - 測試開放式通信通道

[英]Indy 10 TCP Client Server - testing for open communication channel

我正在修改Indy10 TCP / IP應用程序,我希望您的建議/意見/示例代碼實現客戶端功能,執行以下操作

a)在顯示啟動畫面時應用程序啟動時,它會驗證客戶端計算機是否具有Internet訪問權限,並且TCP服務器已啟動並正在運行並等待通信。 如果不是這種情況,應該終止申請。

b)在客戶端和服務器之間進行任何數據交換之前,執行上述(a)

此外,服務器是否需要重復廣播某種消息以通知潛在客戶它已啟動並運行?

謝謝你的協助。

如何驗證是否可以連接到TCP服務器?

對你的第一個問題; 肯定將連接嘗試包裝到一個單獨的線程,您將在啟動屏幕顯示時運行該線程。 在該線程中,您只需嘗試Connect並捕獲異常即可。 如果引發異常,則連接失敗。 如果沒有,你就可以連接。 對於有關此狀態的通知,我將使用自定義消息,您將發送到啟動屏幕表單,如下面的偽代碼所示:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, IdTCPClient;

const
  WM_CONNECTION_NOTIFY = WM_USER + 1;
  SC_CONNECTION_FAILURE = 0;
  SC_CONNECTION_SUCCESS = 1;

type
  TConnThread = class(TThread)
  private
    FMsgHandler: HWND;
    FTCPClient: TIdTCPClient;
  protected
    procedure Execute; override;
  public
    constructor Create(const AHost: string; APort: Word; ATimeout: Integer;
      AMsgHandler: HWND); reintroduce;
    destructor Destroy; override;
  end;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    FConnThread: TConnThread;
    procedure WMConnectionNotify(var AMessage: TMessage); message WM_CONNECTION_NOTIFY;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TConnThread }

constructor TConnThread.Create(const AHost: string; APort: Word;
  ATimeout: Integer; AMsgHandler: HWND);
begin
  inherited Create(False);
  FreeOnTerminate := False;
  FMsgHandler := AMsgHandler;
  FTCPClient := TIdTCPClient.Create(nil);
  FTCPClient.Host := AHost;
  FTCPClient.Port := APort;
  FTCPClient.ConnectTimeout := ATimeout;
end;

destructor TConnThread.Destroy;
begin
  FTCPClient.Free;
  inherited;
end;

procedure TConnThread.Execute;
begin
  try
    FTCPClient.Connect;
    PostMessage(FMsgHandler, WM_CONNECTION_NOTIFY, 0, SC_CONNECTION_SUCCESS);
  except
    PostMessage(FMsgHandler, WM_CONNECTION_NOTIFY, 0, SC_CONNECTION_FAILURE);
  end;
end;

{ TForm1 }

procedure TForm1.FormCreate(Sender: TObject);
begin
  FConnThread := TConnThread.Create('123.4.5.6', 123, 5000, Handle);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FConnThread.Free;
end;

procedure TForm1.WMConnectionNotify(var AMessage: TMessage);
begin
  case AMessage.LParam of
    // the connection failed
    SC_CONNECTION_FAILURE: ;
    // the connection succeeded
    SC_CONNECTION_SUCCESS: ;
  end;
end;

end.

服務器是否需要重復廣播某種消息以通知正在運行的潛在客戶端?

不,這可以在不同的方向工作 - 客戶端詢問服務器是否正在運行。 這就是因為服務器不知道客戶端,但客戶端知道服務器。

“服務器是否需要重復播放某種消息”

有些系統(服務器,服務)使用IP多播主動向感興趣的客戶通告其位置 (IP地址,端口號)甚至附加信息(例如狀態)。

使用Internet Direct(Indy)UDP組件很容易實現服務器端和客戶端端。

以下是Delphi的開源消息代理Apache ActiveMQ的IP多播示例,其中包含完整源代碼:

使用Delphi XE4和Indy 10.6發現ActiveMQ代理

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM