网络中的数据数据传输都是以二进制的形式实现的,所以要想将类从网络的一个断点发送到另一个端点必须将类转换成二进制。delphi中经常使用的方法是将类转换成二进制流,其过程是先将类存入内存流,再将内存流转化成二进制数据。代码如下:
type TStreamBuffer = array[0..ComponentBufferSize] of Byte; Procedure TBaseManage.SendMessage(vHost:string;vPort:integer;vMessage:TBaseMessage); var MemoryStream:TMemoryStream; BF:TStreamBuffer; ResStr:string; begin vMessage.Properties.receiveOptions.IP := vHost; vMessage.Properties.receiveOptions.Port := vPort; if (Self is TClientManager) and (TClientManager(self).CurNodeObject <> nil) then vMessage.Properties.SendOptions.ID := InToStr(TClientManage(self).CurNodeObject.ID); MemoryStream := TMemoryStream.Create; MemoryStream.WriteComponent(vMessage); MemeoryStream.Position := 0; //流中存取指针的位置; ZeroMemory(@BF,MemoryStream.Size); //将分配的内存清零; MemoryStream.Read(BF,MemeoryStream.Size) FSendUDPClient.SendBuffer(vHost,vPort,MemoryStream.Size); ResStr := ''; ResStr := FSendUDPClient.ReceiveString(); MemoryStream.Free; end;