求delphi UDP组播收发端实例
求delphi UDP组播收发端实例
求delphi UDP组播收发端实例
来自GPT:
以下是一个简单的Delphi UDP组播收发端实例:
收端:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent,
IdUDPBase, IdUDPClient, IdSocketHandle, Vcl.StdCtrls;
type
TForm1 = class(TForm)
IdUDPClient1: TIdUDPClient;
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure IdUDPClient1UDPRead(Sender: TObject; AData: TBytes;
ABinding: TIdSocketHandle);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
IdUDPClient1.Active := True;
IdUDPClient1.MulticastGroup := '224.0.0.1'; // 组播地址
IdUDPClient1.Port := 6000; // 端口号
end;
procedure TForm1.IdUDPClient1UDPRead(Sender: TObject; AData: TBytes;
ABinding: TIdSocketHandle);
var
S: string;
begin
S := Trim(TEncoding.UTF8.GetString(AData)); // 转换为字符串
Memo1.Lines.Add(S);
end;
end.
发端:
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdBaseComponent, IdComponent,
IdUDPBase, IdUDPServer, IdSocketHandle, Vcl.StdCtrls;
type
TForm2 = class(TForm)
IdUDPServer1: TIdUDPServer;
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.dfm}
procedure TForm2.Button1Click(Sender: TObject);
begin
IdUDPServer1.Active := True;
IdUDPServer1.Bindings.Add;
IdUDPServer1.Bindings[0].IP := '0.0.0.0'; // 监听所有IP地址
IdUDPServer1.Bindings[0].Port := 6000; // 端口号
IdUDPServer1.Bindings[0].MulticastGroup := '224.0.0.1'; // 组播地址
end;
end.
注意:需要在组播地址范围内选择一个未被占用的地址,一般为224.0.0.0~239.255.255.255。