windows 服务程序和桌面程序集成(三)UDP监控工具

系列文章目录链接:

  1. windows 服务程序和桌面程序集成(一)概念介绍
  2. windows 服务程序和桌面程序集成(二)服务程序
  3. windows 服务程序和桌面程序集成(三)UDP监控工具
  4. windows 服务程序和桌面程序集成(四)桌面程序
  5. windows 服务程序和桌面程序集成(五)集成为一个EXE
  6. windows 服务程序和桌面程序集成(六)集成安装、启动、卸载功能
  7. windows 服务程序和桌面程序集成(七)效果演示及源程序下载
     

在开发windows服务程序和桌面程序中,经常需要UDP监控工具来获取程序运行状态,特别是对于windows服务程序或者是线程,没有界面,很难感知实时运行效果,这样开发一个简单的通用UDP监控工具,就可以监测到windows服务程序或者线程的事实运行状态,如果把UDP消息保存成文件,也就是一种监测日志了。

程序很简单,就是使用Indy的TidUDPServer控件,来实现UDP消息的监听接收。可以指定监听的端口,默认是8192。

提醒:

        如果这里的端口号更改了,那么windows服务中使用的发送UDP消息的客户端端口号也需要修改,需要修改成和这里一样的端口号!

使用的时候打开UDP服务即可,关闭UDP服务就停止监测了。

程序的uMainForm_UDP.pas单元代码如下:

unit uMainForm_UDP;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdUDPServer, IdGlobal, IdSocketHandle,
  IdBaseComponent, IdComponent, IdUDPBase, Vcl.StdCtrls, Vcl.ExtCtrls,
  Vcl.Samples.Spin;

type
  TForm_UDP_Server = class(TForm)
    IdUDPServer: TIdUDPServer;
    Memo1: TMemo;
    Panel1: TPanel;
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    SpinEdit1: TSpinEdit;
    Label1: TLabel;
    procedure IdUDPServerUDPRead(AThread: TIdUDPListenerThread;
      const AData: TIdBytes; ABinding: TIdSocketHandle);
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form_UDP_Server: TForm_UDP_Server;

implementation

{$R *.dfm}

procedure TForm_UDP_Server.Button1Click(Sender: TObject);
begin
   IdUDPServer.Active := False;   //首先关闭
   IdUDPServer.DefaultPort := SpinEdit1.Value;
   try
     IdUDPServer.Active := True;
     Memo1.Lines.Add('UDP 服务打开成功,端口号: ' + IdUDPServer.DefaultPort.ToString);
   except on E: Exception do
     begin
       Memo1.Lines.Add(E.Message);
     end;
   end;
end;

procedure TForm_UDP_Server.Button2Click(Sender: TObject);
begin
  IdUDPServer.Active := False;   //关闭
  Memo1.Lines.Add('UDP 服务已经关闭!');
end;

procedure TForm_UDP_Server.Button3Click(Sender: TObject);
begin
   Memo1.Clear;
end;

procedure TForm_UDP_Server.IdUDPServerUDPRead(AThread: TIdUDPListenerThread;
  const AData: TIdBytes; ABinding: TIdSocketHandle);
var
  data : string;
begin
  //接收到数据,界面
  //处理接收到的数据
  data := ABinding.PeerIP + ':' + ABinding.PeerPort.ToString + '  ' +  TEncoding.UTF8.GetString(TBytes(AData));
  Memo1.Lines.Add(data);
end;

end.

下一篇:windows 服务程序和桌面程序集成(四)桌面程序

猜你喜欢

转载自blog.csdn.net/sensor_WU/article/details/131155257
今日推荐