【发布时间】:2014-02-20 05:58:15
【问题描述】:
我有一段代码,当许多数据包几乎同时从同一来源到达时,它大部分时间都会跳过数据包。构建数据包时,会在开头附加一个数据包大小字段,该字段后面是数据包的大小,以字节为单位。
TCP 客户端线程以 10 毫秒的间隔运行。
线程库
unit AgThread11;
interface
uses
SysUtils, Classes, Windows, Rtti;
type
TAgThreadMethod1 = procedure of object;
TAgThreadMethod2 = procedure;
TAgThread = class ( TThread )
private
fInterval : Cardinal;
fTerminateEvent : THandle;
fRun : Boolean;
fOnRun1 : TAgThreadMethod1;
fOnRun2 : TAgThreadMethod2;
protected
procedure Execute; override;
public
constructor Create
( const AOnRun: TAgThreadMethod1; const AInterval: Cardinal;
const ARun: Boolean = True ); overload;
constructor Create
( const AOnRun: TAgThreadMethod2; const AInterval: Cardinal;
const ARun: Boolean = True ); overload;
destructor Destroy; override;
procedure Signal;
property Run : Boolean read fRun write fRun;
property Interval : Cardinal read fInterval write fInterval;
property OnRun1 : TAgThreadMethod1 read fOnRun1 write fOnRun1;
property OnRun2 : TAgThreadMethod2 read fOnRun2 write fOnRun2;
end;
implementation
constructor TAgThread.Create
( const AOnRun: TAgThreadMethod1; const AInterval: Cardinal;
const ARun: Boolean = True );
begin
fTerminateEvent := CreateEvent ( nil, TRUE, FALSE, nil );
fInterval := AInterval;
fRun := ARun;
fOnRun1 := AOnRun;
inherited Create ( False );
end;
constructor TAgThread.Create
( const AOnRun: TAgThreadMethod2; const AInterval: Cardinal;
const ARun: Boolean = True );
begin
fTerminateEvent := CreateEvent ( nil, TRUE, FALSE, nil );
fInterval := AInterval;
fRun := ARun;
fOnRun2 := AOnRun;
inherited Create ( False );
end;
destructor TAgThread.Destroy;
begin
Terminate;
Signal;
WaitFor;
inherited;
end;
procedure TAgThread.Signal;
begin
SetEvent ( FTerminateEvent );
end;
procedure TAgThread.Execute;
begin
while not Terminated do
begin
if fRun then
if Assigned ( fOnRun1 ) then fOnRun1
else if Assigned ( fOnRun2 ) then fOnRun2;
WaitForSingleObject ( FTerminateEvent, fInterval );
end;
end;
end.
TCP 线程代码
procedure TForm1.THEX_TCP;
var
Buffer : TBytes;
MsgSize : Integer;
begin
if TCPClient.IOHandler.CheckForDataOnSource then
begin
while TCPClient.IOHandler.InputBuffer.Size >= 4 do
begin
fRXCount := fRXCount + 1;
TCPClient.IOHandler.InputBuffer.ExtractToBytes ( Buffer, 4 );
Move ( Buffer [0], MsgSize, 4 );
TCPClient.IOHandler.InputBuffer.ExtractToBytes ( Buffer, MsgSize, False );
NAT.RecievedNATData ( Buffer ); // Packet Processor
end;
end;
end;
如何确保零丢包?
【问题讨论】:
标签: multithreading delphi tcp network-programming indy