function BytestoHexString(ABytes: TBytes; len: Integer): AnsiString; begin SetLength(Result, len*2); BinToHex(@ABytes[0], PAnsiChar(Result), len); end;
例子:
客户端:
IdTCPClient1: TIdTCPClient;
Button1: TButton;
mmo1: TMemo;
procedure TForm4.Button1Click(Sender: TObject);
var
b:TBytes;
Len:Integer;
str:string;
begin
IdTCPClient1.Host:= '127.0.0.1';
IdTCPClient1.Port:= 8090;
if not IdTCPClient1.Connected then
IdTCPClient1.Connect;
if IdTCPClient1.Connected then
begin
IdTCPClient1.IOHandler.WriteLn('QUERYDATA');
mmo1.Lines.Add('向服务器发送:QUERYDATA') ;
try
IdTCPClient1.IOHandler.CheckForDataOnSource(250);//等待
Len:= IdTCPClient1.IOHandler.InputBuffer.Size;
IdTCPClient1.IOHandler.ReadBytes(b,len,false);
mmo1.Lines.Add('接收到:' +BytestoHexString(b,length(b)));
finally
IdTCPClient1.Disconnect;
end;
end;
end;
服务端
IdTCPServer1: TIdTCPServer;
Button1: TButton;
Memo1: TMemo;
procedure TForm4.Button1Click(Sender: TObject);
begin
if IdTCPServer1.Active then
IdTCPServer1.Active:= False;
IdTCPServer1.Bindings.Clear;
with IdTCPServer1.Bindings.Add do
begin
ip:= '0.0.0.0';
Port:= 8090;
end;
IdTCPServer1.DefaultPort:= 8090;
IdTCPServer1.Active:= True;
Memo1.Lines.Add('服务器监听已启动!')
end;
procedure TForm4.IdTCPServer1Execute(AContext: TIdContext);
var
Cmd:string;
b:TBytes;
begin
if not AContext.Connection.IOHandler.Connected then
begin
Exit;
end;
try
Cmd:= AContext.Connection.IOHandler.ReadLn;
Memo1.Lines.Add('接收到数据:'+Cmd);
if Cmd = 'QUERYDATA' then
begin
setlength(b,2);
b[0]:= 1;
b[1]:= 2;
AContext.Connection.IOHandler.Write(b);
Memo1.Lines.Add('发送:'+BytestoHexString(b,Length(b)));
end;
except
Exit;
end;
end;