unit uUDPCommunicate ;interfaceuses SysUtils, Classes, IdUDPClient, IdBaseComponent, IdComponent, IdUDPBase, IdUDPServer, IdAntiFreezeBase, IdAntiFreeze, IdSocketHandle, Dialogs, Forms ;type //定义一个事件格式,要传参数的格式 后面必须要加上of object UDPRecDataEvent = procedure(RecData: String) of object;type TUDPCommunicate = class(TObject) procedure UDPServUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle); private { Private declarations } FUDPRecDataEvent: UDPRecDataEvent ; UDPRecString : String ; UDPServ: TIdUDPServer; UDPClient: TIdUDPClient; AntiFreeze: TIdAntiFreeze; procedure InitComUDP ; function InitUDPServer(Active:boolean): boolean ; function InitUDPClient: boolean ; function ReceiveUDPData(AData: TStream; ABinding: TIdSocketHandle): Boolean; public { Public declarations } constructor Create; destructor Destroy; override; function UDPSendData(SendStr:String; Ip:String):boolean ; property OnUDPRecDataEvent: UDPRecDataEvent read FUDPRecDataEvent write FUDPRecDataEvent ; end;implementation{ TdRoomSynch }constructor TUDPCommunicate.Create;begin inherited; AntiFreeze := TIdAntiFreeze.Create(Application.MainForm) ; InitComUDP ; UDPRecString := '' ;end;destructor TUDPCommunicate.Destroy;begin UDPClient.Free ; UDPServ.Free ; AntiFreeze.Free ; inherited;end;function TUDPCommunicate.ReceiveUDPData(AData: TStream; ABinding: TIdSocketHandle): Boolean;var DataStringStream : TStringStream ;begin Result := False ; if Assigned(FUDPRecDataEvent) then begin UDPRecString := '' ; DataStringStream := TStringStream.Create('') ; DataStringStream.CopyFrom(AData, AData.Size) ; UDPRecString := DataStringStream.DataString ; FUDPRecDataEvent(UDPRecString) ; DataStringStream.Free ; Result := True ; end;end;procedure TUDPCommunicate.InitComUDP;begin InitUDPClient ; InitUDPServer(True) ;end;function TUDPCommunicate.InitUDPClient: boolean;begin UDPClient := TIdUDPClient.Create(Application.MainForm) ; Randomize; UDPClient.BroadcastEnabled := False ; UDPClient.Host := '127.0.0.1' ; UDPClient.Port := TUDPComPort ; UDPClient.BufferSize := TRmSynchBuffer ; UDPClient.ReceiveTimeout := TRmSynchTimeOut ;end;function TUDPCommunicate.InitUDPServer(Active: boolean): boolean;begin UDPServ := TIdUDPServer.Create(Application.MainForm) ; UDPServ.BroadcastEnabled := False ; UDPServ.DefaultPort := TUDPComPort ; UDPServ.BufferSize := TRmSynchBuffer ; UDPServ.OnUDPRead := UDPServUDPRead ; UDPServ.Active := Active ;end;function TUDPCommunicate.UDPSendData(SendStr:String; Ip:String): boolean;begin //发送end;procedure TUDPCommunicate.UDPServUDPRead(Sender: TObject; AData: TStream; ABinding: TIdSocketHandle);begin ReceiveUDPData(AData, ABinding); //接收end;end.