網上關於消息隊列技術原理說明的詳細文檔不少,但涉及到Delphi的具體實現不多,這是我從網上找了一上午的資料,本身整合和嘗試的能運行的程序。spa
打開控制面板->程序->添加組件,添加消息隊列.net
打開控制面板->計算機管理->服務與應用程序->消息隊列,添加私有有消息Test.orm
在Delphi中添加MSMQ控件, TMSMQMessage; TMSMQQueueInfo; TMSMQQueue; TMSMQEvent; 這些控件在Project->Import type Library裏存在。blog
源代碼以下:隊列
unit Unit1; 文檔
interface get
uses 消息隊列
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, it
Dialogs,MSMQ_TLB,ComObj, StdCtrls, OleServer;
type
TForm1 = class(TForm)
MSMQMessage1: TMSMQMessage;
MSMQQueueInfo1: TMSMQQueueInfo;
MSMQQueue1: TMSMQQueue;
MSMQEvent1: TMSMQEvent;
Button1: TButton;
edit1: TEdit;
edit2: TEdit;
Button2: TButton;
lbl1: TLabel;
lbl2: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure MSMQEvent1Arrived(Sender: TObject; var Queue: OleVariant;
Cursor: Integer);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
//發送消息
procedure TForm1.Button1Click(Sender: TObject);
begin
//肯定消息隊列路徑
MSMQQueueInfo1.PathName :='./Private$/Test';
//遠程機器名
MSMQQueueInfo1.RemoteMachineName := '127.0.0.1' ;
//消息內容
(MSMQMessage1.DefaultInterface as IMSMQMessage).body :=edit1.Text;
//鏈接到消息隊列
MSMQQueue1.ConnectTo(MSMQQueueInfo1.Open(MQ_SEND_ACCESS, 0));
//發送消息
MSMQMessage1.Send(MSMQQueueInfo1.Open(MQ_SEND_ACCESS, MQ_DENY_NONE));
showmessage( '已經把信息入寫入消息隊列中 ');
end;
//接收消息
procedure TForm1.Button2Click(Sender: TObject);
begin
msmqqueueinfo1.PathName :='./Private$/Test';
msmqqueue1.Disconnect;
msmqqueue1.ConnectTo(msmqqueueinfo1.Open(1, 0));
//
msmqqueue1.EnableNotification(MSMQEvent1.DefaultInterface);
end;
//MSMQEvent事件
procedure TForm1.MSMQEvent1Arrived(Sender: TObject; var Queue: OleVariant;
Cursor: Integer);
var
Msg: Variant;
begin
//從隊列中讀取消息
Msg := msmqqueue1.Receive;
edit2.Text := Msg.body;
end;
end.