发送结构体:
TMyData = record
id:Integer;
Name:Array[0..20] of Char;
Sex:Array[0..10] of Char;
Age:Byte;
Address:Array[0..256] of Char;
UpdateTime:double;
end;
//发送结构体:
procedure TForm2.Button2Click(Sender: TObject);
var
SendData:TMyData;
begin
SendData.ID:=10;
StrPCopy(SendData.Name,'Wyatt');
StrPCopy(SendData.Sex,'男');
SendData.age:=25;
StrPCopy(SendData.Address,'江苏省');
SendData.UpdateTime:=Now;
IdTCPClient1.IOHandler.Write(#99);//接收时便于区分接收的数据类型 自定义
IdTCPClient1.IOHandler.Write(RawToBytes(SendData,SizeOf(SendData)));
end;
//发送TStrings类型
procedure TForm2.Button3Click(Sender: TObject);
var
sList:TStrings;
I:Integer;
begin
sList := TStringList.Create;
for I :=0 to 30 do
begin
sList.Add('数据index' + IntToStr(i));
end;
IdTCPClient1.IOHandler.Write(#111);//接收时便于区分接收的数据类型 自定义
IdTCPClient1.IOHandler.Write(sList.Count);
IdTCPClient1.IOHandler.Write(ToBytes(sList.Text,TIdTextEncoding.UTF8));
end;
//发送一行字符串数据
procedure TForm2.Button4Click(Sender: TObject);
begin
IdTCPClient1.IOHandler.Write(#12);//接收时便于区分接收的数据类型 自定义
IdTCPClient1.IOHandler.Write('文星',TIdTextEncoding.UTF8);//中文要指定编码,接收时也要进行相应的转换,否则中文会显示成?号
end;
接收:
procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var
ReadData:TMyData;
buf:TIdBytes;
sCmd:Char;
sList:TStrings;
I:Integer;
ListCount:Integer;
begin
sCmd := AContext.Connection.IOHandler.ReadChar;
if sCmd = #99 then //接收结构体
begin
AContext.Connection.IOHandler.ReadBytes(buf,SizeOf(ReadData));
BytesToRaw(buf, ReadData, SizeOf(ReadData));
with Memo1.lines do
begin
Add('ID:'+Inttostr(ReadData.Id));
Add('Name:'+StrPas(ReadData.Name));
Add('Sex:'+ReadData.sex);
Add('Age:'+Inttostr(ReadData.age));
Add('UpdateTime:'+DateTimeToStr(ReadData.UpdateTime));
end;
end
else if sCmd = #111 then //接收 TStrings
begin
ListCount := AContext.Connection.IOHandler.ReadLongInt;
sList := TStringList.Create;
try
AContext.Connection.IOHandler.ReadStrings(sList,ListCount,TIdTextEncoding.UTF8);
for I :=0 to sList.Count-1 do
begin
Memo1.Lines.Add(sList.Strings[I]);
end;
finally
sList.Free;
end;
end
else if sCmd = #12 then
begin
Memo1.Lines.Add(AContext.Connection.IOHandler.ReadString(AContext.Connection.IOHandler.InputBuffer.Size,TIdTextEncoding.UTF8)
end
else
AContext.Connection.IOHandler.InputBuffer.Clear;//清除不能识别的命令
);
end;