
以下代码在Windows2003下测试通过:
using System;
using System.Messaging;
namespace ConsoleApplication1
{
class Program
{
static readonly string MQPATH = @".\private$\MzwuCom";
/// <summary>
/// 程序入口
/// </summary>
/// <param name="args">
/// 发送消息:mq.exe c hello
/// 接收消息:mq.exe r
/// </param>
static void Main(string[] args)
{
if (args.Length == 1 && args[0].ToLower() == "r")
{
string msg = MQReceive();
if (msg.Substring(0, 1) == "1")
Console.WriteLine("收到队列消息:{0}", msg.Substring(2));
else
Console.WriteLine("接收队列消息失败:{0}", msg.Substring(2));
}
else if (args.Length == 2 && args[0].ToLower() == "c")
{
if (MQSend(args[1]))
Console.WriteLine("发送消息到队列:{0}", args[1]);
else
Console.WriteLine("发送消息到队列失败!");
}
else
{
Console.WriteLine("命令行参数错误!");
}
}
/// <summary>
/// 创建消息队列
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
static MessageQueue MQCreate(string path)
{
try
{
if (!MessageQueue.Exists(path))
return MessageQueue.Create(path);
else
return new MessageQueue(path);
}
catch { }
return null;
}
/// <summary>
/// 发送消息到队列
/// </summary>
/// <param name="msg"></param>
/// <returns></returns>
static bool MQSend(string msg)
{
using (MessageQueue mq = MQCreate(MQPATH))
{
if (mq != null)
{
Message message = new Message();
[color=Red]message.Recoverable = true;//系统重启后消息不丢失[/color]
message.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
message.Body = msg;
mq.Send(message);
return true;
}
else
{
return false;
}
}
}
/// <summary>
/// 接收一条消息
/// </summary>
/// <returns></returns>
static string MQReceive()
{
string result = "队列中暂无消息!";
try
{
using (MessageQueue mq = MQCreate(MQPATH))
{
if (mq != null)
{
mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });
using (Message msg = mq.Receive(TimeSpan.FromSeconds(5)))
{
return "1|" + msg.Body.ToString();
}
}
else
result = "创建MessageQueue对象失败!";
}
}
catch (Exception ex)
{
result = ex.Message;
}
return "0|" + result;
}
}
}
评论(0)
暂无评论。