關於網絡中查找服務器主機的問題,似乎可以使用UDP廣播的方式查找。
先看代碼:
1.unit ClIEntUnit;
2.
3.interface
4.
5.uses
6. Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
7. Dialogs, StdCtrls, ExtCtrls, IDBaseComponent, IdComponent, IdUDPBase,
8. IdUDPClIEnt, IdAntiFreezeBase, IdAntiFreeze;
9.
10.type
11. TClIEntForm = class(TForm)
12. Label1: TLabel;
13. Edit1: TEdit;
14. Button1: TButton;
15. Label2: TLabel;
16. IdUDPClient1: TIdUDPClIEnt;
17. IdAntiFreeze1: TIdAntiFreeze;
18. ListBox1: TListBox;
19. Timer1: TTimer;
20. procedure Button1Click(Sender: TObject);
21. procedure FormCreate(Sender: TObject);
22. procedure Timer1Timer(Sender: TObject);
23. private
24. { Private declarations }
25. var IpList : TStringList;
26. public
27. { Public declarations }
28. end;
29.
30.var
31. ClientForm: TClIEntForm;
32.
33.implementation
34.
35.{$R *.dfm}
36.
37.procedure TClIEntForm.Button1Click(Sender: TObject);
38.begin
39. IdUDPClIEnt1.Broadcast(Edit1.Text, 3030);
40. ListBox1.Items.Add(IdUDPClIEnt1.ReceiveString());
41.end;
42.
43.procedure TClIEntForm.FormCreate(Sender: TObject);
44.begin
45. IdUDPClIEnt1.ReceiveTimeout := 10000;
46.
47. IpList := TStringList.Create;
48.end;
49.
50.procedure TClIEntForm.Timer1Timer(Sender: TObject);
51.var ipaddr : string;
52.var I : Integer;
53.begin
54. IdUDPClIEnt1.BroadcastEnabled := True;
55. IdUDPClIEnt1.Broadcast('SearchHost', 3030);
56. ipaddr := IdUDPClIEnt1.ReceiveString();
57. if IpList.IndexOf(ipaddr) = -1 then
58. IpList.Add(ipaddr);
59.
60. ListBox1.Clear;
61. for I := 0 to IpList.Count - 1 do
62. ListBox1.Items.Add(IpList.Strings[I]);
63.end;
64.
65.end.
這樣在IpList中就會不斷的有主機的IP地址被加入進來了。
但是實際情況是這樣的:
由於使用了TTimer控件,我這裡設置了Interval:5000,如果設置過小會因為線程大量占用而嚴重影響主程序正常工作,不知道有什麼辦法來解決這個問題。還有,當網絡中沒有服務器的任何響應時客戶端也會出現假死現象,不知如何解決。