全部博文(788)
分类:
2008-10-28 10:00:15
up
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer,IdSocketHandle;
type
TForm1 = class(TForm)
IdUDPServer1: TIdUDPServer;
procedure FormCreate(Sender: TObject);
procedure IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
begin
IdUDPServer1.Active:=False;
IdUDPServer1.DefaultPort:=6100;
IdUDPServer1.Active:=True;
end;
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
begin
//写你侦听的代码,你可以参考随代的DEMO
end;
end.
//uses部分需要才动加上IdSocketHandle单元
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.DefaultPort:=6100;
UDPServer.Active := not UDPServer.Active;
if UDPServer.Active then Caption := 'True' else Caption := 'False';
end;
end.
刚写的一个例子
demo好像已经实现了!我的理解有点问题:)