I try to send a string from a tidtcpserver to a tidtcpclient in Delphi, but when i send a string the client receives nothing. I don't get any errors. I am using tstringstream because i want to send a base64 string(writeln/readln can't send/receive that much text) This is the send code in idtcpserver1:
procedure TForm1.sendtext(index:integer; txt:string);
var
StrStream:tStream;
List: TList;
AContext: TIdContext;
begin
txt := trim(txt);
strstream := TMemoryStream.Create;
strstream.Write(PAnsiChar(txt)^, Length(txt));
strstream.Position := 0;
List := idTcpServer1.Contexts.LockList;
AContext := TIdContext(List[index]);
AContext.Connection.IOHandler.write(StrStream);
idTcpServer1.Contexts.UnLockList;
end;
This is the read code in idtcpclient1
procedure TIndyClient.Execute;
var
StrStream:tStringStream;
receivedtext:string;
begin
StrStream := tstringstream.Create;
form1.IdTCPClient1.IOHandler.readstream(StrStream);
receivedtext := strstream.DataString;
if receivedtext = '' = false then
begin
showmessage(receivedtext);
end;
end;
Does anyone know what i am doing wrong?
You are making a very common newbie mistake of mismatching the
IOHandler.Write(TStream)andIOHandler.ReadStream()calls. By default,ReadStream()expects the stream data to be preceded by the stream size, butWrite(TStream)does not send the stream size by default.Try this instead:
Alternatively, because the stream size is now being sent, the receiving code can use
ReadString()instead ofReadStream():BTW,
WriteLn()/ReadLn()do not have any length restrictions, they can handle big strings as long as there is available memory (and the text being sent does not have any line breaks in it). You are probably being confused byReadLn()being subject to theIOHandler.MaxLineLength, which is set to 16K characters by default, but you can bypass that: