以下是C#通过MSMQ向远程消息队列服务器发送消息的完整实现方法(RemoteMsmqSender.cs):
using System;
using System.Messaging;
public class RemoteMsmqSender
{
// 远程队列路径格式:FormatName:DIRECT=TCP:IP地址\private$\队列名
private const string REMOTE_QUEUE_PATH = "FormatName:DIRECT=TCP:192.168.1.100\\private$\\remote_queue";
public static void SendMessage(string messageContent)
{
try
{
// 创建消息队列连接(无需本地队列存在)
using (MessageQueue queue = new MessageQueue(REMOTE_QUEUE_PATH))
{
// 设置消息格式为字符串
queue.Formatter = new XmlMessageFormatter(new[] { typeof(string) });
// 构建消息对象
Message msg = new Message
{
Body = messageContent,
Label = "C# Client Message",
Recoverable = true // 确保消息持久化
};
// 发送消息(事务性发送需使用MessageQueueTransaction)
queue.Send(msg);
Console.WriteLine($"消息已发送至远程队列:{messageContent}");
}
}
catch (MessageQueueException ex)
{
Console.WriteLine($"MSMQ错误:{ex.Message}");
// 常见错误码处理
if (ex.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
Console.WriteLine("连接超时,请检查网络和远程队列状态");
}
}
}
}
关键点说明:
1、远程路径必须使用FormatName指定协议和IP
2、需确保远程服务器已启用MSMQ并开放防火墙端口(默认1801)
3、事务性消息需使用MessageQueueTransaction类
主程序(Program.cs):
class Program
{
static void Main()
{
// 发送测试消息
RemoteMsmqSender.SendMessage("Hello from remote client at " + DateTime.Now);
// 发送复杂对象(需序列化)
var order = new { OrderId = 1001, Product = "Laptop" };
RemoteMsmqSender.SendMessage(Newtonsoft.Json.JsonConvert.SerializeObject(order));
}
}
注意事项:
远程服务器需在Active Directory中注册(域环境)或配置匿名访问权限
大消息需设置Message.BodyStream属性替代直接赋值
生产环境建议添加消息加密(使用Message.EncryptionAlgorithm)
查看更多关于C#发送消息给远程消息队列服务器的方法的详细内容...