刚刚试过了,代码如下,我的版本是9.0.1
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer,
IdStack, IdSocketHandle;
type
TForm1 = class(TForm)
UDPServer: TIdUDPServer;
Button1: TButton;
Memo1: TMemo;
BufferSizeLabel: TLabel;
PortLabel: TLabel;
HostAddressLabel: TLabel;
HostNameLabel: TLabel;
procedure FormCreate(Sender: TObject);
procedure UDPServerUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
HostNameLabel.Caption := UDPServer.LocalName;
HostAddressLabel.Caption := GStack.LocalAddress;
PortLabel.Caption := IntToStr(UDPServer.DefaultPort);
BufferSizeLabel.Caption := IntToStr(UDPServer.BufferSize);
UDPServer.Active := True;
end;
procedure TForm1.UDPServerUDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
DataStringStream: TStringStream;
s: String;
begin
DataStringStream := TStringStream.Create('');
try
DataStringStream.CopyFrom(AData, AData.Size);
Memo1.Lines.Add('Received "' + DataStringStream.DataString + '" from ' +
ABinding.PeerIP + ' on port ' + IntToStr(ABinding.PeerPort));
s := 'Replied from ' + UDPServer.LocalName + ' to "' +
DataStringStream.DataString + '"';
ABinding.SendTo(ABinding.PeerIP, ABinding.PeerPort, s[1], Length(s));
finally
DataStringStream.Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if UDPServer.Active then Caption := 'True' else Caption := 'False';
UDPServer.Active := not UDPServer.Active;
if UDPServer.Active then Caption := 'True' else Caption := 'False';
end;
end.