I have a TCP "Server", that is sending data every 20 seconds. I am trying to receive this data and display the result. Currently, the data is displayed 3 times instead of once. It then waits another 20 seconds, and again displays the data 3 times.
with Client do
begin
Connect;
while True do
begin
try
if IOHandler.CheckForDataOnSource(1000) then
begin
WriteLn('Bytes available: ' IntToStr(IOHandler.InputBuffer.Size));
IOHandler.ReadBytes(buffer, IOHandler.InputBuffer.Size);
end;
except
on e : exception do
writeln(e.message);
end;
if(buffer <> nil) then
begin
SetString(msg, PAnsiChar(@buffer[0], length(buffer));
buffer := nil;
IOHandler.InputBuffer.Clear;
end;
write(msg);
end;
end;
I fixed the problem I was having, by moving the write(msg) into the if statement checking if the buffer is not nil.
with Client do
begin
Connect;
while True do
begin
try
if IOHandler.CheckForDataOnSource(1000) then
begin
WriteLn('Bytes available: ' IntToStr(IOHandler.InputBuffer.Size));
IOHandler.ReadBytes(buffer, IOHandler.InputBuffer.Size);
end;
except
on e : exception do
writeln(e.message);
end;
if(buffer <> nil) then
begin
SetString(msg, PAnsiChar(@buffer[0], length(buffer));
buffer := nil;
IOHandler.InputBuffer.Clear;
write(msg); {only write out the message when the buffer is not nil}
end;
end;
end;