百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

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

zhezhongyun 2025-01-13 19:13 70 浏览

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:\Study\SSE' + 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如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        window.onload = ()=> {

			console.log("onload!");
            if (window.EventSource) {
                let source = new EventSource("/subscribe");
                let s = '';
                // 
                source.addEventListener('message', function(e) {
                    console.log("connect message");
                    document.querySelector("p").innerText = e.data;
                })
                source.addEventListener('open',function(e){
                    console.log("connect is open");
                },false);
                source.addEventListener('error',function(e){
                    if(e.readyState == EventSource.CLOSE){
                        console.log("connect is close");
						console.log('connection state: ' + source.readyState + ', error: ' + event); 
						console.log(event); 
                    }else{
                        console.log(e.readyState);
                    }
                },false);
            } else {
                alert("浏览器不支持EventSource");
            }
        }
    </script>
</head>
<body>
    <p></p>
</body>
</html>

编译版是Delphi 10.4.2

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

相关推荐

perl基础——循环控制_principle循环

在编程中,我们往往需要进行不同情况的判断,选择,重复操作。这些时候我们需要对简单语句来添加循环控制变量或者命令。if/unless我们需要在满足特定条件下再执行的语句,可以通过if/unle...

CHAPTER 2 The Antechamber of M de Treville 第二章 特雷维尔先生的前厅

CHAPTER1TheThreePresentsofD'ArtagnantheElderCHAPTER2TheAntechamber...

CHAPTER 5 The King&#39;S Musketeers and the Cardinal&#39;S Guards 第五章 国王的火枪手和红衣主教的卫士

CHAPTER3TheAudienceCHAPTER5TheKing'SMusketeersandtheCardinal'SGuard...

CHAPTER 3 The Audience 第三章 接见

CHAPTER3TheAudienceCHAPTER3TheAudience第三章接见M.DeTrévillewasatt...

别搞印象流!数据说明谁才是外线防守第一人!

来源:Reddit译者:@assholeeric编辑:伯伦WhoarethebestperimeterdefendersintheNBA?Here'sagraphofStea...

V-Day commemorations prove anti-China claims hollow

People'sLiberationArmyhonorguardstakepartinthemilitaryparademarkingthe80thanniversary...

EasyPoi使用_easypoi api

EasyPoi的主要特点:1.设计精巧,使用简单2.接口丰富,扩展简单3.默认值多,writelessdomore4.springmvc支持,web导出可以简单明了使用1.easypoi...

关于Oracle数据库12c 新特性总结_oracle数据库12514

概述今天主要简单介绍一下Oracle12c的一些新特性,仅供参考。参考:http://docs.oracle.com/database/121/NEWFT/chapter12102.htm#NEWFT...

【开发者成长】JAVA 线上故障排查完整套路!

线上故障主要会包括CPU、磁盘、内存以及网络问题,而大多数故障可能会包含不止一个层面的问题,所以进行排查时候尽量四个方面依次排查一遍。同时例如jstack、jmap等工具也是不囿于一个方面的问题...

使用 Python 向多个地址发送电子邮件

在本文中,我们将演示如何使用Python编程语言向使用不同电子邮件地址的不同收件人发送电子邮件。具体来说,我们将向许多不同的人发送电子邮件。使用Python向多个地址发送电子邮件Python...

提高工作效率的--Linux常用命令,能够决解95%以上的问题

点击上方关注,第一时间接受干货转发,点赞,收藏,不如一次关注评论区第一条注意查看回复:Linux命令获取linux常用命令大全pdf+Linux命令行大全pdf为什么要学习Linux命令?1、因为Li...

linux常用系统命令_linux操作系统常用命令

系统信息arch显示机器的处理器架构dmidecode-q显示硬件系统部件-(SMBIOS/DMI)hdparm-i/dev/hda罗列一个磁盘的架构特性hdparm-tT/dev/s...

小白入门必知必会-PostgreSQL-15.2源码编译安装

一PostgreSQL编译安装1.1下载源码包在PostgreSQL官方主页https://www.postgresql.org/ftp/source/下载区选择所需格式的源码包下载。cd/we...

Linux操作系统之常用命令_linux系统常用命令详解

Linux操作系统一、常用命令1.系统(1)系统信息arch显示机器的处理器架构uname-m显示机器的处理器架构uname-r显示正在使用的内核版本dmidecode-q显示硬件系...

linux网络命名空间简介_linux 网络相关命令

此篇会以例子的方式介绍下linux网络命名空间。此例中会创建两个networknamespace:nsa、nsb,一个网桥bridge0,nsa、nsb中添加网络设备veth,网络设备间...