还不会主动向前端通过SSE推送消息? 看这篇就会了![Delphi版]

SSE(Server-Send Events)

SSE 是一种在基于浏览器的 Web 应用程序中仅从服务器向客户端发送文本消息的技术。SSE基于 HTTP 协议中的持久连接, 具有由 W3C 标准化的网络协议和 EventSource 客户端接口,作为 HTML5 标准套件的一部分。

使用其他方法实现的很多,采用Delphi实现的却基本没有,请教了一位高手,在他的帮助下实现了,特写下来,希望能帮助到更多的delphier.

废话不多说,直接上代码!

pas如下

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdCustomHTTPServer, IdHTTPServer,IdTCPConnection,
  IdBaseComponent, IdComponent, IdCustomTCPServer, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    IdHTTPServer1: TIdHTTPServer;
    Memo1: TMemo;
    Button1: TButton;
    Edit1: TEdit;
    procedure FormCreate(Sender: TObject);
    procedure IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
      AResponseInfo: TIdHTTPResponseInfo);
    procedure Button1Click(Sender: TObject);
  private
    procedure SendSSEMessage(const AMessage: string);
  public
  end;

var
    Form1: TForm1;
   gConnection : TIdTCPConnection;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
    SendSSEMessage(Edit1.Text);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    IdHTTPServer1.DefaultPort := 80; // 设置服务器端口
    IdHTTPServer1.ServerSoftware := 'Delphi SSE Server'; // 设置服务器名称  IdHTTPServer1.Active := True;
    idHttpServer1.Active    := True;
    Memo1.Lines.Add('Server started...');
end;

procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext; ARequestInfo: TIdHTTPRequestInfo;
    AResponseInfo: TIdHTTPResponseInfo);
var
    LFilename: string;
    LPathname: string;
begin
    LFilename := ARequestInfo.Document;
    LPathname := 'E:StudySSE' + LFilename;
    if FileExists(LPathname) then begin
        AResponseInfo.ContentStream := TFileStream.Create(LPathname, fmOpenRead + fmShareDenyWrite);
    end else begin
        if ARequestInfo.URI = '/subscribe' then begin
            with AContext.Connection.IOHandler do begin
                WriteBufferOpen;
                WriteLn('HTTP/1.1 200 OK');
                WriteLn('Content-Type: text/event-stream; charset=UTF-8');
                WriteLn('Cache-Control: no-cache');
                WriteLn('Connection: keep-alive');
                WriteLn();
                WriteBufferClose;

            end;

            //
            gConnection   := AContext.Connection;
        end;
    end;
end;

procedure TForm1.SendSSEMessage(const AMessage: string);
begin
    with gConnection.IOHandler do begin
        WriteBufferOpen;
        WriteLn('id:'+IntToStr(random(1000))+#13#10);
        WriteLn('event:test'+#13#10);
        WriteLn('data:'+AMessage+#13#10#13#10);
        WriteBufferClose;
    end;
end;

end.

dfm如下:

object Form1: TForm1
  Left = 0
  Top = 0
  Caption = 'Form1'
  ClientHeight = 242
  ClientWidth = 601
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'Tahoma'
  Font.Style = []
  OldCreateOrder = False
  OnCreate = FormCreate
  PixelsPerInch = 96
  TextHeight = 13
  object Memo1: TMemo
    Left = 250
    Top = 0
    Width = 351
    Height = 242
    Align = alRight
    Lines.Strings = (
      'Memo1')
    TabOrder = 0
    ExplicitLeft = 512
  end
  object Button1: TButton
    Left = 48
    Top = 168
    Width = 75
    Height = 25
    Caption = 'Button1'
    TabOrder = 1
    OnClick = Button1Click
  end
  object Edit1: TEdit
    Left = 48
    Top = 32
    Width = 121
    Height = 21
    TabOrder = 2
    Text = 'Edit1'
  end
  object IdHTTPServer1: TIdHTTPServer
    Bindings = <>
    TerminateWaitTime = 50000
    KeepAlive = True
    SessionTimeOut = 50000
    OnCommandGet = IdHTTPServer1CommandGet
    Left = 120
    Top = 80
  end
end

对应的HTML如下:




    
    Title
    


    

编译版是Delphi 10.4.2

点击Button1,即可向前端推送Edit1中的字符串。

展开阅读全文

页面更新:2024-04-25

标签:套件   字符串   特写   端口   应用程序   持久   废话   客户端   主动   协议   消息   服务器

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top