这个简单,用indy控件就行了。
---------------------
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, StdCtrls,IdSocketHandle;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
IdUDPServer1: TIdUDPServer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
//初始化 .................
if IdUDPServer1.Active then IdUDPServer1.Active:=false;
IdUDPServer1.Bindings.Clear;
//侦听本机所有IP的12345端口
with IdUDPServer1.Bindings.Add do
begin
ip:='0.0.0.0' ;
port:=12345;
end;
//同时还侦听本机某个IP 的 54321端口 (可选)
with IdUDPServer1.Bindings.Add do
begin
ip:='188.188.21.49' ;
port:=54321;
end;
try
IdUDPServer1.Active :=true;
except
On E:Exception do Memo1.Lines.Add(e.Message);
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//发送数据 测试
IdUDPServer1.Send('127.0.0.1',12345,'127.0.0.1-Test12345'); //正常
IdUDPServer1.Send('188.188.21.49',12345,'188.188.21.49-Test12345'); //正常
IdUDPServer1.Send('188.188.21.49',54321,'188.188.21.49-Test54321'); //正常
IdUDPServer1.Send('127.0.0.1',54321,'Test127.0.0.1-54321'); //不能收到,因为没有进行侦听
end;
procedure TForm1.IdUDPServer1UDPRead(Sender: TObject; AData: TStream;
ABinding: TIdSocketHandle);
var
buff:array [1..1000] of char;
i,Len:integer;
str:string;
begin
//接收数据。。。
Len := aData.Size ;
aData.ReadBuffer(buff,Len);
str:='';
for i := 0 to Len do
str:=str+buff;
Memo1.Lines.Add(ABinding.PeerIP + ':'
+ inttostr(ABinding.PeerPort) + '>'
+ str);
end;
end.