我知道我之前发布过类似的问题,但我无法让它工作,我有这个简单的代码:
procedure TfrmMain.srvrConnect(AContext: TIdContext); //idhttpserver on connect event
var
S,C : String;
begin
repeat
s := s + AContext.Connection.Socket.ReadChar;
until AContext.Connection.Socket.InputBufferIsEmpty = True;
frmMain.caption := S;
Memo1.Lines.Add(S);
end;
字符串在备忘录中显示正常,但标题未更新
最佳答案
TIdHTTPServer
是一个多线程组件。 TIdContext
在其自己的工作线程中运行。您无法从主线程外部安全地更新表单的 Caption
(或对 UI 执行任何其他操作)。您需要与主线程同步,例如与 TIdSync
或 TIdNotify
类同步。
顺便说一句,在循环中调用 ReadChar()
效率非常低,更不用说如果您使用 Delphi 2009+ 则容易出错,因为它无法返回代理项对的数据。
使用更像这样的东西来代替;
type
TDataNotify = class(TIdNotify)
protected
Data: String;
procedure DoNotify; override;
public
constructor Create(const S: String);
class procedure DataAvailable(const S: String);
end;
constructor TDataNotify.Create(const S: String);
begin
inherited Create;
Data := S;
end;
procedure TDataNotify.DoNotify;
begin
frmMain.Caption := Data;
frmMain.Memo1.Lines.Add(Data);
end;
class procedure TDataNotify.DataAvailable(const S: String);
begin
Create(S).Notify;
end;
procedure TfrmMain.srvrConnect(AContext: TIdContext); //idhttpserver on connect event
var
S: String;
begin
AContext.Connection.IOHandler.CheckForDataOnSource(IdTimeoutDefault);
if not AContext.Connection.IOHandler.InputBufferIsEmpty then
begin
S := AContext.Connection.IOHandler.InputBufferAsString;
TDataNotify.DataAvailable(S);
end;
end;
关于delphi - IdHttpServer 表单标题未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9784257/