我有一个TCP" Server",即每20秒发送一次数据。我试图接收这些数据并显示结果。目前,数据显示3次而不是一次。然后再等待20秒,再次显示数据3次。
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;
答案 0 :(得分:2)
无论您是否真正读取任何新数据,您都会在每次循环迭代时调用write(msg)
。您在将buffer
分配给msg
后将其重置为零,但在编写后msg
未将''
重置为msg
。因此,每次循环迭代都会写入已经存在的任何with Client do
begin
Connect;
buffer := nil;
repeat
try
if IOHandler.CheckForDataOnSource(1000) then
begin
WriteLn('Bytes available: ' + IntToStr(IOHandler.InputBuffer.Size));
IOHandler.ReadBytes(buffer, IOHandler.InputBuffer.Size);
SetString(msg, PAnsiChar(buffer), Length(buffer));
Write(msg);
buffer := nil;
end;
except
on E: Exception do
WriteLn(E.Message);
end;
until not Connected;
end;
,直到为其分配新值。
请尝试使用此代码:
with Client do
begin
Connect;
buffer := nil;
repeat
try
IOHandler.ReadBytes(buffer, -1);
WriteLn('Bytes read: ' + Length(buffer));
SetString(msg, PAnsiChar(buffer), Length(buffer));
Write(msg);
buffer := nil;
except
on E: Exception do
WriteLn(E.Message);
end;
until not Connected;
end;
可以简化为:
with Client do
begin
Connect;
repeat
try
if IOHandler.CheckForDataOnSource(IdTimeoutDefault) then
begin
WriteLn('Bytes available: ' + IntToStr(IOHandler.InputBuffer.Size));
Write(IOHandler.InputBufferAsString(en8bit));
end;
except
on E: Exception do
WriteLn(E.Message);
end;
until not Connected;
end;
甚至:
{{1}}
答案 1 :(得分:0)
我修复了我遇到的问题,将write(msg)移动到if语句中检查缓冲区是否为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;