How can I update HTML pages dynamically with Indy HTTP server using jQuery and “Long Polling”?

前端 未结 1 692
萌比男神i
萌比男神i 2021-02-09 06:15

I have read the article Simple Long Polling Example with JavaScript and jQuery. The paragraph \"Long Polling - An Efficient Server-Push Technique\" explains that

1条回答
  •  孤独总比滥情好
    2021-02-09 06:30

    Here is a self-contained example project, tested with Indy version 10.5.9 and Delphi 2009.

    When the application runs, navigate to http://127.0.0.1:8080/. The server will then serve a HTML document (hard-coded in the OnCommandGet handler).

    This document contains a div element which will be used as the container for new data:

    
      
    Server time is:
    '

    The JavaScript code then send requests to the resource /getdata in a loop (function poll()).

    The server responds with a HTML fragment which contains a new

    element with the current server time. The JavaScript code then replaces the old
    element with the new.

    To simulate server work, the method waits for one second before returning the data.

    program IndyLongPollingDemo;
    
    {$APPTYPE CONSOLE}
    
    uses
      IdHTTPServer, IdCustomHTTPServer, IdContext, IdSocketHandle, IdGlobal,
      SysUtils, Classes;
    
    type
      TMyServer = class(TIdHTTPServer)
      public
        procedure InitComponent; override;
        procedure DoCommandGet(AContext: TIdContext;
          ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo); override;
      end;
    
    procedure Demo;
    var
      Server: TMyServer;
    begin
      Server := TMyServer.Create(nil);
      try
        try
          Server.Active := True;
        except
          on E: Exception do
          begin
            WriteLn(E.ClassName + ' ' + E.Message);
          end;
        end;
        WriteLn('Hit any key to terminate.');
        ReadLn;
      finally
        Server.Free;
      end;
    end;
    
    procedure TMyServer.InitComponent;
    var
      Binding: TIdSocketHandle;
    begin
      inherited;
    
      Bindings.Clear;
      Binding := Bindings.Add;
      Binding.IP := '127.0.0.1';
      Binding.Port := 8080;
    
      KeepAlive := True;
    end;
    
    procedure TMyServer.DoCommandGet(AContext: TIdContext;
      ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
    begin
      AResponseInfo.ContentType := 'text/html';
      AResponseInfo.CharSet := 'UTF-8';
    
      if ARequestInfo.Document = '/' then
      begin
        AResponseInfo.ContentText :=
          '' + #13#10
          + '' + #13#10
          + 'Long Poll Example' + #13#10
          + '   ' + #13#10
          + '  ' + #13#10
          + '' + #13#10
          + ' ' + #13#10
          + '  
    Server time is:
    ' + #13#10 + '' + #13#10 + '' + #13#10; end else begin Sleep(1000); AResponseInfo.ContentText := '
    '+DateTimeToStr(Now)+'
    '; end; end; begin Demo; end.

    0 讨论(0)
提交回复
热议问题