【发布时间】:2015-02-21 02:34:52
【问题描述】:
几周前我开始使用 Indy TCPServer 和 TCPClient,现在,经过 SOF 专家(特别是 Lebeau 先生)的大量研究和帮助,我可以安全地管理客户端连接并向特定客户端发送字符串消息。这是一段代码:
type
TClient = class(TObject)
private
FHost: string;
public
FQMsg: TIdThreadSafeStringList; // Message Queue
constructor Create(const Host: string);
destructor Destroy; override;
end;
procedure TfrmMain.TCPServerExecute(AContext: TIdContext);
var
Client: TClient;
LQueue: TStringList;
WQueue: TStringList;
begin
with AContext.Connection.IOHandler Do
begin
DefStringEncoding := TEncoding.UTF8;
LQueue := nil;
Client := TClient(AContext.Data);
try
WQueue := Client.FQMsg.Lock;
try
if (WQueue.Count > 0) then
begin
LQueue := TStringList.Create;
LQueue.Assign(WQueue);
WQueue.Clear;
end;
finally
Client.FQMsg.Unlock;
end;
if (LQueue <> nil) then
Write(LQueue);
finally
LQueue.Free;
end;
end;
end;
现在是时候更进一步,尝试从客户那里得到答复。但是突然间我意识到我不能使用 TCPServer 的 OnExecute 事件来“同时”发送消息和接收答案??我可能错了,但这段代码不起作用,我不知道为什么......
procedure TfrmMain.TCPServerExecute(AContext: TIdContext);
var
RStr: string;
Client: TClient;
LQueue: TStringList;
WQueue: TStringList;
begin
with AContext.Connection.IOHandler Do
begin
DefStringEncoding := TEncoding.UTF8;
// Send Cmd
LQueue := nil;
Client := TClient(AContext.Data);
try
WQueue := Client.FQMsg.Lock;
try
if (WQueue.Count > 0) then
begin
LQueue := TStringList.Create;
LQueue.Assign(WQueue);
WQueue.Clear;
end;
finally
Client.FQMsg.Unlock;
end;
if (LQueue <> nil) then
Write(LQueue);
finally
LQueue.Free;
end;
// Receive Data
RStr := Trim(ReadLn);
if (RStr <> '') then
begin
SyncLog(RStr);
end;
end;
end;
当我将最后一部分 (ReadLn) 添加在一起时,代码的第一部分不起作用,我无法再向客户端发送消息:(
拜托,有人知道我错过了什么吗?
谢谢!
【问题讨论】: