Delphi下MSMQ(Mircosoft Message Queue)实例(私有队列)

网上关于消息队列技术原理说明的详细文档很多,但涉及到Delphi的具体实现很少,这是我从网上找了一上午的资料,自己整合和尝试的能运行的程序。

打开控制面板->程序->添加组件,添加消息队列

打开控制面板->计算机管理->服务与应用程序->消息队列,添加私有有消息Test.

在Delphi中添加MSMQ控件, TMSMQMessage; TMSMQQueueInfo; TMSMQQueue; TMSMQEvent; 这些控件在Project->Import type Library里存在。

源代码如下:

[c-sharp] view plain copy
 
  1. unit Unit1;  
  2. interface  
  3. uses  
  4.   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  
  5.   Dialogs,MSMQ_TLB,ComObj, StdCtrls, OleServer;  
  6. type  
  7.   TForm1 = class(TForm)  
  8.     MSMQMessage1: TMSMQMessage;  
  9.     MSMQQueueInfo1: TMSMQQueueInfo;  
  10.     MSMQQueue1: TMSMQQueue;  
  11.     MSMQEvent1: TMSMQEvent;  
  12.     Button1: TButton;  
  13.     edit1: TEdit;  
  14.     edit2: TEdit;  
  15.     Button2: TButton;  
  16.     lbl1: TLabel;  
  17.     lbl2: TLabel;  
  18.     procedure Button1Click(Sender: TObject);  
  19.     procedure Button2Click(Sender: TObject);  
  20.     procedure MSMQEvent1Arrived(Sender: TObject; var Queue: OleVariant;  
  21.       Cursor: Integer);  
  22.   private  
  23.     { Private declarations }  
  24.   public  
  25.     { Public declarations }  
  26.   end;  
  27. var  
  28.   Form1: TForm1;  
  29. implementation  
  30. {$R *.dfm}  
  31. //发送消息  
  32. procedure TForm1.Button1Click(Sender: TObject);  
  33. begin  
  34.     //确定消息队列路径  
  35.     MSMQQueueInfo1.PathName       :='./Private$/Test';  
  36.     //远程机器名  
  37.     MSMQQueueInfo1.RemoteMachineName   :=   '127.0.0.1'   ;  
  38.     //消息内容  
  39.     (MSMQMessage1.DefaultInterface   as   IMSMQMessage).body   :=edit1.Text;  
  40.     //连接到消息队列  
  41.     MSMQQueue1.ConnectTo(MSMQQueueInfo1.Open(MQ_SEND_ACCESS,       0));  
  42.     //发送消息  
  43.     MSMQMessage1.Send(MSMQQueueInfo1.Open(MQ_SEND_ACCESS,       MQ_DENY_NONE));  
  44.     showmessage( '已经把信息入写入消息队列中 ');  
  45. end;  
  46. //接收消息  
  47. procedure TForm1.Button2Click(Sender: TObject);  
  48. begin  
  49.   msmqqueueinfo1.PathName   :='./Private$/Test';  
  50.   msmqqueue1.Disconnect;  
  51.   msmqqueue1.ConnectTo(msmqqueueinfo1.Open(1,   0));  
  52.   //  
  53.   msmqqueue1.EnableNotification(MSMQEvent1.DefaultInterface);  
  54. end;  
  55. //MSMQEvent事件  
  56. procedure TForm1.MSMQEvent1Arrived(Sender: TObject; var Queue: OleVariant;  
  57.   Cursor: Integer);  
  58.       var  
  59.   Msg:   Variant;  
  60.   begin  
  61.   //从队列中读取消息  
  62.   Msg   :=   msmqqueue1.Receive;  
  63.   edit2.Text :=   Msg.body;  
  64. end;  
  65. end.  

可以连续发送多条不同的消息。消息会添加到消息队列。每“接收”一次会从消息队列中获取一条消息并显示在接受消息框中。

原文地址:https://www.cnblogs.com/h2zZhou/p/8275217.html