How Can I Delphi 2009 & Indy 10 TCPServer & TCPClient & Stream ? [Edit]

How can i send simple XML data from TCPClient to TCPServer and opposite.
The Indy Version is the Delphi 2009 shipped version (v10). I have some XML data (you can think it as TStrings).
I Can not convert the xml string to stream and send it to server then can't convert from stream sent to server to TStrings (or string) again in server (or client) side...

Thanks for code snippets & answers...

Edited by: Huseyin Melih Kara on Apr 27, 2009 7:59 AM

Edited by: Huseyin Melih Kara on Apr 28, 2009 5:24 AM
0
HM
4/28/2009 2:24:47 AM
embarcadero.delphi.winsock 1874 articles. 2 followers. Follow

11 Replies
2595 Views

Similar Articles

[PageSpeed] 7
Get it on Google Play
Get it on Apple App Store

> {quote:title=Huseyin Melih Kara wrote:}{quote}
> How can i send simple XML data from TCPClient to TCPServer and opposite.
> The Indy Version is the Delphi 2009 shipped version (v10). I have some XML data (you can think it as TStrings).
> I Can not convert the xml string to stream and send it to server then can't convert from stream sent to server to TStrings (or string) again in server (or client) side...
> 
> Thanks for code snippets & answers...

Hello,
here is some snippets from working code (BDS2006 & Indy10, also transferring XML via Streams)
Client :
{code}
procedure TfrmClient.Send(sData : String);
var
  msData : TMemoryStream;
  k : Integer;
begin
  if idTCPClient.Connected then
  begin
    try
      msData := TMemoryStream.Create;
      k := Length(sData);
      msData.WriteBuffer(k, SizeOf(Integer));
      msData.WriteBuffer(sData[1], Length(sData));
      msData.Position := 0;
      idTCPClient.IOHandler.Write(msData, sizeof(Integer)+Length(sData), true);
    finally
      FreeAndNil(msData);
    end;
  end;
end;
{code}
Info : the above code uses a feature of Indy, it preceeds the tcp data with its length, but it isn't necessary to do so

Server (execute) :
{code}
procedure TMyTcpSrv.HandleServerExecute(AContext: TIdContext);
var
  msin: TMemoryStream;
  countin: Integer;
  DataIn: String;
  Abort: Boolean;
begin
  Abort := false;
  DataIn := '';

  msin := TMemoryStream.Create;
  try
    try
      try
        AContext.Connection.IOHandler.ReadStream(msin);
      except
        on e: EIdConnClosedGracefully do
        begin
          Abort := true;
        end else
          raise;
      end;

      if not Abort then
      begin
        msin.Position := 0;
        msin.ReadBuffer(countin,SizeOf(Integer));
        SetLength(DataIn,countin);
        msin.ReadBuffer(DataIn[1],countin);
      end;
    except
      on e: Exception do
      begin
        DataIn := '';
        if Assigned(FLog) then
          FLog.WriteError(self,e.ClassName + ' Exception while reading incoming data: '+ e.Message);
      end;
    end;
  finally
    msin.Free;
  end;
....
{code}
Note here also the 2 readbuffers, one to read the length of the data, and the second one reading the data.

The only difference is that I use normal strings and not TStrings, but it works fine.

HTH,
Michael
0
Michael
4/28/2009 9:36:03 AM
Thanks for your asnwer Michael,
But when i directly use your codes in my test program; It will only get the first 324 chars of the xml and its bigger than this (not too big may be about 1000 chars total), and got no errors. i send from client like: Send(XML.Text);
Is there any reason why is that happening?

Thanks again...
0
HM
4/28/2009 7:50:42 PM
"Huseyin Melih Kara" escribió en el mensaje de noticias 
news:110580@forums.codegear.com...
> Thanks for your asnwer Michael,
> But when i directly use your codes in my test program; It will only get 
> the first 324 chars of the xml and its bigger than this (not too big may 
> be about 1000 chars total), and got no errors. i send from client like: 
> Send(XML.Text);
> Is there any reason why is that happening?
>
> Thanks again...

In D2009 sizeof(Char) is 2. Try

{code}
msData.WriteBuffer(sData[1], Length(sData)*sizeof(Char));
msData.Position := 0;
idTCPClient.IOHandler.Write(msData, msData.Size, true);
{code}
0
Antonio
4/28/2009 8:17:35 PM
"Antonio Estevez" <amelsoft@terra.es> escribió en el mensaje de noticias 
news:110599@forums.codegear.com...
> "Huseyin Melih Kara" escribió en el mensaje de noticias
> news:110580@forums.codegear.com...
>> Thanks for your asnwer Michael,
>> But when i directly use your codes in my test program; It will only get
>> the first 324 chars of the xml and its bigger than this (not too big may
>> be about 1000 chars total), and got no errors. i send from client like:
>> Send(XML.Text);
>> Is there any reason why is that happening?
>>
>> Thanks again...
>
> In D2009 sizeof(Char) is 2. Try
>
> {code}
> msData.WriteBuffer(sData[1], Length(sData)*sizeof(Char));
> msData.Position := 0;
> idTCPClient.IOHandler.Write(msData, msData.Size, true);
> {code}

And, of course, in HandleServerExecute:

{code}
        msin.Position := 0;
        msin.ReadBuffer(countin,SizeOf(Integer));
        SetLength(DataIn,countin);
        msin.ReadBuffer(DataIn[1],countin*SizeOf(Char));
{code}
0
Antonio
4/28/2009 8:46:53 PM
if i make the changes as you said i got "stream read error" ?
0
HM
4/28/2009 11:32:15 PM
{quote:title=Huseyin Melih Kara wrote:}{quote}

> How can i send simple XML data from TCPClient to TCPServer and opposite.
> The Indy Version is the Delphi 2009 shipped version (v10). I have some XML data
> (you can think it as TStrings). I Can not convert the xml string to stream and send
> it to server then can't convert from stream sent to server to TStrings (or string)
> again in server (or client) side...

Keep in mind that D2009 is Unicode now.  Trying to send and receive TStrings with Indy will perform Unicode->Ansi and Ansi->Unicode conversions internally.  If you are having troubles with the data, then you are likely not telling Indy to encode/decode it properly.  Please show your actual code, and please show the actual data you are trying to send.

--
Remy Lebeau (TeamB)
0
Remy
4/29/2009 5:06:10 AM
> {quote:title=Remy Lebeau (TeamB) wrote:}{quote}
> {quote:title=Huseyin Melih Kara wrote:}{quote}
> 
> > How can i send simple XML data from TCPClient to TCPServer and opposite.
> > The Indy Version is the Delphi 2009 shipped version (v10). I have some XML data
> > (you can think it as TStrings). I Can not convert the xml string to stream and send
> > it to server then can't convert from stream sent to server to TStrings (or string)
> > again in server (or client) side...
> 
> Keep in mind that D2009 is Unicode now.  Trying to send and receive TStrings with Indy will perform Unicode->Ansi and Ansi->Unicode conversions internally.  If you are having troubles with the data, then you are likely not telling Indy to encode/decode it properly.  Please show your actual code, and please show the actual data you are trying to send.
> 
> --
> Remy Lebeau (TeamB)

Thanks for the reply,
_*For The Server:*_

{code}
//Michael Diwo's code
procedure TfrmMain.ServerExecute(AContext: TIdContext);
var
  Stream: TMemoryStream;
  Count: Integer;
  Data: String;
  Abort: Boolean;
begin
  Abort := false;
  Data := '';
  Stream := TMemoryStream.Create;
  try
    try
      try
        AContext.Connection.IOHandler.ReadStream(Stream);
      except
        on e: EIdConnClosedGracefully do
        begin
          Abort := true;
        end else
          raise;
      end;
      if not Abort then
      begin
        Stream.Position := 0;
        Stream.ReadBuffer(Count,SizeOf(Integer));
        SetLength(Data,Count);
        Stream.ReadBuffer(Data[1],Count);
      end;
    except
      on e: Exception do
      begin
        Data := '';
      end;
    end;
  finally
    Stream.Free;
  end;
  edtlog.Lines.Text := Data;
end;
{code}

_*For The Client:*_

{code}
procedure TForm1.Send(sData : String);
var
  msData : TMemoryStream;
  k : Integer;
begin
  if Client.Connected then
  begin
    try
      msData := TMemoryStream.Create;
      k := Length(sData);
      msData.WriteBuffer(k, SizeOf(Integer));
      msData.WriteBuffer(sData[1], Length(sData));
      msData.Position := 0;
      Client.IOHandler.Write(msData, sizeof(Integer)+Length(sData), true);
    finally
      FreeAndNil(msData);
    end;
  end;
end;
{code}

_*and simply from a button on the client form:*_

{code}
procedure TForm1.Button1Click(Sender: TObject);
begin
  if client.Connected = false then client.Connect;
  Send(memo1.Lines.Text);
end;
{code}

The edtlog from server form and memo1 from client form is a TMemo component in delphi 2009.

and the XML data in the memo is:

{code}
<?xml version="1.0" encoding="windows-1254"?>
<GAME>
	<DATA>
		<Information1>True</Information1>
		<Information2>Some Information # 2</Information2>
		<Information3>Some Information # 3</Information3>
		<Information4>Some Information # 4</Information4>
		<Information5>Some Information # 5</Information5>
		<Information6>Some Information # 6</Information6>
		<Information7>Some Information # 7</Information7>
		<NumbersCount>10</NumbersCount>
			<NUMBERS>
				<Number>1</Number>
				<Number>3</Number>
				<Number>5</Number>
				<Number>9</Number>
				<Number>12</Number>
				<Number>33</Number>
				<Number>56</Number>
				<Number>32</Number>
				<Number>10</Number>
				<Number>25</Number>
			</NUMBERS>
	</DATA>
</GAME>
{code}

But when i send this data from client to server
the server got only:

{code}
<?xml version="1.0" encoding="windows-1254"?>
<GAME>
	<DATA>
		<Information1>True</Information1>
		<Information2>Some Information # 2</Information2>
		<Information3>Some Information # 3</Information3>
		<Information4>Some Information # 4</Information4>
		<Information5>Some Information # 5</Information5>
		<Information6>Some Information # 6</Information6>
		<Infor
{code}

Thanks for your helps...
0
HM
4/29/2009 7:15:29 PM
Can someone solve this?
0
HM
5/1/2009 12:00:34 PM
<Huseyin Melih Kara> wrote in message news:111093@forums.codegear.com...

>  Data: String;

'String' map to UnicodeString in D2009, not AnsiString anymore.  Your server 
code is expecting to receive Ansi data, and thus will not work correctly 
with a UnicodeString variable as you have shown.  Your client code is also 
not handling UnicodString variables correctly, either.  It is not taking 
into account that Indy 10 convert Unicode values to Ansi by default, but 
does so in a way that will not preserve the Unicode data correctly if the 
server is not using the same language as the client.  You should change your 
code on both ends to use UTF-8 instead, ie:

{code:delphi}
procedure TfrmMain.ServerExecute(AContext: TIdContext);
begin
  with AContext.Connection.IOHandler do
    edtlog.Lines.Text := ReadString(ReadInteger, TIdTextEncoding.UTF8);
end;
{code}

{code:delphi}
procedure TForm1.Send(const sData : String);
begin
  if Client.Connected then
  begin
      Client.IOHandler.Write(TIdTextEncoding.GetByteCount(sData));
      Client.IOHandler.Write(sData, TIdTextEncoding.UTF8);
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  if not Client.Connected then Client.Connect;
  Send(Memo1.Lines.Text);
end;
{code}

> and the XML data in the memo is:

Since you are using Unicode strings in your code, you should be using 
"UTF-16" instead of "windows-1254" as the XML's encoding.  Or use "UTF-8" 
since that is what the code above is using for transmitting the XML (but 
then you would have to put the XML data into a TStream or UT8String instead 
of a UnicodeString or even an AnsiString).

-- 
Remy Lebeau (TeamB)
0
Remy
5/2/2009 7:40:05 AM
Thanks for your answer,

I got "E2076 This form of method call only allowed for class methods" error for 
TIdTextEncoding.GetByteCount(sData));

I try to create as an object but this time i got "abstract error".
and i upgrade my indy to v10.5.5 (02 May 09)...
0
HM
5/3/2009 12:09:39 PM
<Huseyin Melih Kara> wrote in message news:112215@forums.codegear.com...

> I got "E2076 This form of method call only allowed for class methods"
> error for TIdTextEncoding.GetByteCount(sData));

Use this instead:

{code:delphi}
Client.IOHandler.Write(TIdTextEncoding.UTF8.GetByteCount(sData));
Client.IOHandler.Write(sData, TIdTextEncoding.UTF8);
{code}

Alternatively:

{code:delphi}
procedure TForm1.Send(const sData : String);
var
  LEncoding: TIdTextEncoding;
begin
  if Client.Connected then
  begin

    LEncoding := TIdTextEncoding.UTF8;
    Client.IOHandler.Write(LEncoding.GetByteCount(sData));
    Client.IOHandler.Write(sData, LEncoding);
  end;
end;
{code}

Alternatively:

{code:delphi}
procedure TForm1.Send(const sData : String);
var
  LStream: TStream;
begin
  if Client.Connected then
  begin

    LStream := TMemoryStream.Create;
    try
      WriteStringToStream(sData, TIdTextEncoding.UTF8);
      Client.IOHandler.Write(LStream, 0, True);
    finally
      LStream.Free;
    end;
  end;
end;
{code}

-- 
Remy Lebeau (TeamB)
0
Remy
5/4/2009 6:33:37 PM
Reply:

Similar Artilces:

&& In Generated Javascript Becomes &amp;&amp;
I am trying to write client side scripts in c#, asp.net V 1.4. The && operator is generated in the javascript as &amp;amp;, which causes errors.  How can I avoid this? (Code below)  Thanks in advance.   script = "<script language='javascript' type='text/javascript'>\n"; script += "if (Form1." + tbxA.ClientID + ".value == '' && "; script += "Form1." + tbxB.ClientID + ".value == '') {"; script += "Form1." + cbxC.ClientID + ".Checked = false;}"; ...

Delphi 7 & SOAP & WSDL Import & SSRS
Hi I am struggling with a web service I consumed (ReportService2010.asmx). I am not sure if I consumed it with the in-corrections options or if I am not setting THTTPRIO settings correctly or both ! I am really new to webservice & SOAP. I update the Delphi SOAP Runtime and Importer Update (http://cc.embarcadero.com/Item/24535). Thank you Jean-Marie Babet. I imported the WSDL with the following options [wfDebug,wfUnwindLiteralParameters,wfUseSerializerClassForAttrs]. I had to make a few changes to the pas file to get it to compile. I changed {code} SensitivityEnum = (True, Fals...

CrystallReport XI & Delphi 2009 & Sql2000 ?
CrystallReport XI & Delphi 2009 & Sql2000 I installed the component of crystallReport11 in delphi 2009 and added 2 objects in delphi (Crpe,CrpeDS) When I create a report(for example rep1.rpt) in crystall for sql2000 I can preview(Run) it from delphi But I want 1- can set report connection from delphi like : servername , userId ,Pass,Databasename 2- can send my query from delphi to crystal 3- send parametters from delphi to crystal How can do this Thanks error Error:756 Failed to open the connection rep1.rpt details: Database vendor code: 17 SQL.SetQuer...

Convert &amp; to &
I have a Gridview that is populated by the 3 different users from selections made in a prior Form.  This gridview summarizes everything.  I then step through this Gridview and write the data to a history file on SQL. The problem I am having is, one column in this Gridview is a name column which contains the "&" symbol.  When I iterate the Gridview and populate the history file the & becomes &amp;.  I can't seem to figure out how to convert this properly.  Both data fields are nvarchar type.  Please help anyone. This is the code to tak...

If & =&amp; in xml then { or }= what?
Hi frnds, some problem when using xml & is not compatible in xml file so we replace & with &amp;    like that i want to know what the characters which are not compatible with xml syntax for example when i m using { or } in xml file then its shwoing error msg. if anyone knows the soln then plz reply me. Thanks in advance.Regards,Hasan Mohiuddin Farooqihasan_farooqi@yahoo.co.in Hi Dear,Please find the Table. It contains the all special character list... quot " U+0022 (34) HTML 2.0 HTMLspecial ISOnum quotation mark (= APL quote) amp &am...

Replacement of & , &amp;
I was trying this java script inside a mozilla extension but the browser shows me error this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); XML Parsing Error: not well-formed at replace(/&/g,'&amp;') Any thoughts ? Thanks On Fri, 30 May 2008 10:26:19 -0700 (PDT), sb wrote: > I was trying this java script inside a mozilla extension but the > browser shows me error > this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); > ...

& turning to &amp;
I'm doing an operation reformat and trying to use the & in a text box. In the trace it looks ok in the policy, but when it gets to the actual xml value it turns into this: <modify-attr attr-name="EG"> <remove-all-values/> <add-value> <value>&amp;</value> </add-value> </modify-attr> Can I fix this in policy builder or by escaping the character somehow? Or do I need a stylesheet to fix the problem? -- nate_spears ------------------------------------------------------------------------ It isn't a p...

&amp; instead of &
I have gridview with the following code on row commandDim row As GridViewRow = gvBusinessLines.Rows(e.CommandArgument)txtBusinessLine.Text = CStr(row.Cells(1).Text) ''''''''''''''''''''''''''''''''''''''''''''''' When I have this text in gridview for example:"test & test2", when clicking on the button of the gridview, textbox is containing test &amp; test2How to avoide this other than re...

& where shown as &amp;
hai,     At runtime i will add values from textbox to datagrid using datatables.what my problem was , when i add as he & she in textbox it show as he &amps; she in the grid.how to solve this. Thanks in advance   cool.mugil:    At runtime i will add values from textbox to datagrid using datatables.what my problem was , when i add as he & she in textbox it show as he &amps; she in the grid.how to solve this.  Make sure you are not HTML encoding the input values.  Hai,    How to do stop html enc...

&, &&, and backtracking.
------=_Part_20601_33098141.1189046184291 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit Content-Disposition: inline How do C<&> and C<&&> differ with respect to backtracking? For instance, "foobar" ~~ / <[a..z]>+ & [ ... ] /; Both sides of the C<&> happen in parallel, so I would guess that they both match "foo" then stop. Please correct me if that's wrong. Were we using the procedural conjunction: "foobar" ~~ / <[a..z]>+ && [ ... ] /; I would gues...

Kfarbair.com
Name: LeceHoigree Email: 101atmanga-kenseidotcom Product: eBay Companion Summary: Kfarbair.com - &#1489;&#1497;&#1514; &#1502;&#1500;&#1493;&#1503; &#1499;&#1508;&#1512;&#1497; & &#1495;&#1491;&#1512;&#1497;&#1501; &#1502;&#1512;&#1493;&#1493;&#1495;&#1497;&#1501; & &#1499;&#1508;&#1512; &#1489;&#1506;&#1497;&#1512; Comments: <a href=http://www.kfarbair.com><img>http://www.kfarbair.com/_images/_photos/photo_big8.jpg</img></a> ...

&amp;
C:\Program Files\ASP.NET Starter Kits\ASP.NET Portal (VBSDK)\PortalVBSDK\admin\Cardholders.aspx(174) : error BC30451: Name 'amp' is not declared.            __output.Write(Global.GetApplicationPath(Request) &amp; "/ASPNETPortal.css")                                                   ...

and, or, &&, ||
Hello! I remember someone mentioning that there may be a precedence problem with "unexpected results" during a mathematical conditional test, using the keywords "and" and "or"...instead of the symbols (&& and ||). Is this true? Can anyone give me an example? Thanks much! cl __________________________________________________ Do You Yahoo!? Get email alerts & NEW webcam video instant messaging with Yahoo! Messenger. http://im.yahoo.com On Tue, 25 Sep 2001, Christine Lenda wrote: > I remember someone mentioning that there may b...

Converting Delphi 2007 Indy 10.2.3 to Delphi 2009 Indy 10.5.5 [Edit]
Hello, I am currently attempting to port over a Delphi 2007 project that uses Indy 10.2.3 (very successfully) to Delphi 2009 and Indy 10.5.5 (I just got the latest development build this morning). I think I am running into an encoding issue, but am not sure. Specifically, IDHTTP with SSL calls an old CGI and the CGI returns a .zip file and I then save it to the disk. In 2007 and before this worked perfectly. In 2009, it is not. Here is the examples of the 2 different results (though cut way short in the post) I am getting back: 2007: 'PK'#3#4#$14#0#0#0#8#0'rLQ9žrPb€'#0...

Web resources about - How Can I Delphi 2009 & Indy 10 TCPServer & TCPClient & Stream ? [Edit] - embarcadero.delphi.winsock

Mixin - Wikipedia, the free encyclopedia
In object-oriented programming languages , a mixin is a class that provides a certain functionality to be inherited or just reused by a subclass, ...

.NetRap - Developer Blog
... the .NetRap Software to your AUG DevKit. Please note that the Software is still a beta, for testing purposes only! After you active the TCPServer ...

qmail is a vector for CVE-2014-6271 (bash "shellshock") - Qmail - users
qmail is a vector for CVE-2014-6271 (bash "shellshock") Qmail users

My Take on Georgi Guninski's qmail Security Advisories
In The qmail security guarantee ,D. J. Bernstein denies that Guninski found (as of May 2005) an exploitable bug in qmail-smtpd .I don't disagree ...

Trivial Non-Blocking Echo Server (Scala+Akka)
Akka is a framework for asynchronous messaging and IO in Scala . A colleague of mine gave it a good recommendation so I thought I’d check it ...

Realtime Questions - Stack Exchange
Stack Exchange sign up log in meta about Stack Exchange All Sites Top Users Newsletters Blogs Stack Exchange Q&A communities are different. Here's ...

Client/Server Model - STSdb W4.0
STSdb W4.0 Client/Server Model. Access your data regardless of the running platform.

bytereef.org
Things you might be looking for: Software: enigma-suite libmpdec cdecimal Papers: papers A formal proof for the stability of mergesort: mergesort-stable ...

Full Disclosure: Windows 7 , Server 2008R2 Remote Kernel Crash
=============================================- Release date: November 11th, 2009- Discovered by: Laurent Gaffié- Severity: Medium/High====== ...

Resources last updated: 11/26/2015 9:37:14 AM