Question

I try to send data shorter than 255 length in Client side.

I try to send data with this protocol :

Lenghth+String
Byte+string
sample :
string = ABCD
sentdata = 4ABCD

here is my server side code:

procedure TfrmServer.tcpsrvr1Accept(Sender: TObject;
  ClientSocket: TCustomIpClient);
  var
  a : array of byte;
  I : Cardinal;
  mystr : string;
  b,Len : Byte;
begin
  ClientSocket.ReceiveBuf(b,1,0);// first try : get lenght
  Len := b;
  SetLength(a,Len+1);
  mmoRerult.Lines.Add(DateTimeToStr(now) + ' Data Len ' +
                  IntToStr(Len));
  ClientSocket.ReceiveBuf(a,Len,0); // second try : this lone is not worked.

  mystr := '';
  for I := 1 to 10 do
  begin
    mystr := mystr + Chr(a[i]);
  end;
  mmoRerult.Lines.Add(mystr);
  //Creating a stream
  mmoRerult.Lines.Add('--------------------');

end;

Problem is if I read all data in first possible first try, But if I read data in second try is not possible,not possible mean is the data is not correct, I think the read pointer is get front, but how can I reset.

And ClientSocket.BytesReceived don't give me count of byte received before read.

How can I fix this problem, Please don't tell me read 255 byte in first I know this way.

Était-ce utile?

La solution

You are reading the data into the pointer rather than the buffer. Fix it like this:

ClientSocket.ReceiveBuf(pointer(a)^,Len,0);

It would be much easier to read directly into an AnsiString variable mind you.

var
  str: AnsiString;
....
SetLength(str, Len);
ClientSocket.ReceiveBuf(pointer(str)^,Len,0);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top