TWinSocketStream.WaitForData, how does it know if I intend to read or write?
I am creating a TCP client / server using TClientSocket / TServerSocket in blocking mode. Proof of Concept The server has already been built and tested for basic functionality (to retrieve data) using telnet. There will be two streams on the client, one for writing and the other for reading. Now, to test "Send (or write) a stream", I use the following code. But stream.WaitForData (30000) always expires. Delphi help says " call WaitForData before reading or writing socket connection information. " So I am wondering how TWinSockStream knows that I am calling WaitForData for writing and not reading?
procedure TClientThread.Execute;
var
stream: TWinSocketStream;
buffer: string;
begin
stream := TWinSocketStream.Create(FClientSocket.Socket, 60000);
try
while (not Terminated) and (FClientSocket.Active) do
begin
try
//FSendDataEvent is a trigger used for testing purpose
if FSendDataEvent.WaitFor(1000) = wrSignaled then
begin
FSendDataEvent.ResetEvent;
if stream.WaitForData(30000) then
begin
buffer := 'Hello from client';
stream.Write(buffer, Length(buffer) + 1 );
end;
end;
//Other useful code
except
on E:Exception do
begin
DebugOutput('TClientThread.Execute: ' + E.Message);
end;
end;
end;
finally
stream.free;
end;
end;
Even if WaitForData () is removed, the text is not passed to the Server as it is. But the following code works fine when called directly - without WaitForData ().
FClientSocket.Socket.SendText('Hi from client');
So what is the correct way to use TWinSocketStream with TClientSocket?
Any help would be appreciated.
source to share
The documentation is wrong. WaitForData()
works read-only, not write.
As far as writing data with using TWinSocketStream
, you are passing the wrong value in the first parameter Write()
, so it doesn't send correctly. The first parameter is untyped const
, so you need to read the string to pass the memory address of the first character, for example:
Stream.Write(Buffer[1], ...);
Or:
Stream.Write(PChar(Buffer)^, ...);
source to share