delphi - IdHttpServer 表单标题未更新

标签 delphi indy

我知道我之前发布过类似的问题,但我无法让它工作,我有这个简单的代码:

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 执行任何其他操作)。您需要与主线程同步,例如与 TIdSyncTIdNotify 类同步。

顺便说一句,在循环中调用 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/

相关文章:

delphi - Pascal 中区分大小写(以 Integer 为例)

Delphi - 将物理路径(设备文件句柄)转换为虚拟路径

delphi - TCP服务器和Error1400

delphi - IdHTTP 使用哪种传输协议(protocol)

sql - 使用 MERGE 语句将记录更新/插入到表中

delphi - TLabel 和 TGroupbox 标题在调整大小时闪烁

delphi - 如何使用 Indy TIdTCPClient 实例从 Web 服务器检索完整的 HTTP 响应,包括响应主体?

delphi - 使用 Indy 组件(Delphi XE6)在 Post 上添加 Cookie?

delphi - 调试 SOAP 传输

html - 如何在 Delphi 中将简单的 RichText 转换为 HTML 标签?