TIdTCPServer
需要OnExecute
默认分配的事件处理程序。为了解决这个问题,您必须从虚拟方法派生一个新类TIdTCPServer
并覆盖其虚拟CheckOkToBeActive()
方法,并且还应该覆盖DoExecute()
调用的虚拟方法Sleep()
。否则,只需分配一个事件处理程序并让它调用Sleep()
.
但是,这不是 的有效使用TIdTCPServer
。更好的设计是不要直接从方法内部将出站数据写入客户端SendMessage()
。这不仅容易出错(您不会从 捕获异常WriteBuffer()
)并在写入期间阻塞SendMessage()
,而且还会序列化您的通信(客户端 2 无法接收数据,直到客户端 1 首先接收数据)。一个更有效的设计是给每个客户端自己的线程安全的出站队列,然后SendMessage()
根据需要将数据放入每个客户端的队列中。然后,您可以使用该OnExecute
事件检查每个客户端的队列并进行实际写入。这样,SendMessage()
不再被阻塞,更不容易出错,并且客户端可以并行写入(就像它们应该的那样)。
尝试这样的事情:
uses
..., IdThreadSafe;
type
TMyContext = class(TIdServerContext)
private
FQueue: TIdThreadSafeStringList;
FEvent: TEvent;
public
constructor Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TThreadList = nil); override;
destructor Destroy; override;
procedure AddMsgToQueue(const Msg: String);
function GetQueuedMsgs: TStrings;
end;
constructor TMyContext.Create(AConnection: TIdTCPConnection; AYarn: TIdYarn; AList: TThreadList = nil);
begin
inherited;
FQueue := TIdThreadSafeStringList.Create;
FEvent := TEvent.Create(nil, True, False, '');
end;
destructor TMyContext.Destroy;
begin
FQueue.Free;
FEvent.Free;
inherited;
end;
procedure TMyContext.AddMsgToQueue(const Msg: String);
begin
with FQueue.Lock do
try
Add(Msg);
FEvent.SetEvent;
finally
FQueue.Unlock;
end;
end;
function TMyContext.GetQueuedMsgs: TStrings;
var
List: TStringList;
begin
Result := nil;
if FEvent.WaitFor(1000) <> wrSignaled then Exit;
List := FQueue.Lock;
try
if List.Count > 0 then
begin
Result := TStringList.Create;
try
Result.Assign(List);
List.Clear;
except
Result.Free;
raise;
end;
end;
FEvent.ResetEvent;
finally
FQueue.Unlock;
end;
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
TCPServer.ContextClass := TMyContext;
end;
procedure TFormMain.TCPServerExecute(AContext: TIdContext);
var
List: TStrings;
I: Integer;
begin
List := TMyContext(AContext).GetQueuedMsgs;
if List = nil then Exit;
try
for I := 0 to List.Count-1 do
AContext.Connection.IOHandler.Write(List[I]);
finally
List.Free;
end;
end;
procedure TFormMain.SendMessage(const IP, Msg: string);
var
I: Integer;
begin
with TCPServer.Contexts.LockList do
try
for I := 0 to Count-1 do
begin
with TMyContext(Items[I]) do
begin
if Binding.PeerIP = IP then
begin
AddMsgToQueue(Msg);
Break;
end;
end;
end;
finally
TCPServer.Contexts.UnlockList;
end;
end;