Newsgroups : Borland : borland.public.delphi.internet.winsock : 2007 Apr : Re: A polite request for Advice on using Sockets
| Subject: | Re: A polite request for Advice on using Sockets |
| Posted by: | "Remy Lebeau (TeamB)" (no.spam@no.spam.com) |
| Date: | Tue, 10 Apr 2007 10:22:20 |
"DC" <egg@egg.ns.com> wrote in message
news:461b5a44@newsgroups.borland.com...
> the string I send seems to get garbled.
Then you are not sending it correctly.
> GetMem(SendBuf, Length(SendStr)+1);
> StrPCopy( SendBuf, SendStr);
You don't need that. You can send the original String directly:
S.Write(PChar(SendStr), Length(SendStr)+1);
Or:
S.Write(Pointer(SendStr), Length(SendStr)+1);
> BytesRead := S.Read(ReadBuf, SizeOf(ReadBuf));
> Memo2.Text := Memo2.Text + String(ReadBuf);
You are not using BytesRead for anything. You should be looking at
its actual value to make sure the read was successful before
attempting to use the received data. Also, depending on the timing,
you may not be guaranteed to have the null terminator, so you should
be using BytesRead to know how many bytes are actually usable, ie:
var
Stream : TWinsocketStream;
S : String;
ReadBuf : Array[0..4095] Of Char;
BytesRead : Integer;
begin
ClientSocket1.Port := 9999;
ClientSocket1.Host := '127.0.0.1';
ClientSocket1.ClientType := ctBlocking;
ClientSocket1.Open;
try
Stream := TWinSocketStream.Create(ClientSocket1.Socket,
5000);
try
S := '1=325617' + #10 + '2=0' + #10 + '3=2.56' + #10 +
'99=0' + #10;
Stream.Write(PChar(S), Length(S)+1);
BytesRead := Stream.Read(ReadBuf, SizeOf(ReadBuf));
if BytesRead > 0 then
begin
SetString(S, ReadBuf, BytesRead);
// this is more efficient than using the Text
property...
Memo2.SelStart := Memo2.GetTextLen;
Memo2.SelLength := 0;
Memo2.SelText := S;
end;
finally
Stream.Free;
end;
finally
ClientSocket1.Close;
end;
end;
Gambit
none