繁体   English   中英

MSMQ自定义消息格式

[英]MSMQ custom message format

我想在MSMQ中发送消息,例如带有文本的消息

<order><data id="5" color="blue"/></order>

这是标准的XML。 到目前为止,我已经做了Serializable类

[Serializable]
public class order
string id
string color

我正在使用BinaryFormatter。 当我检查message.BodyStream时,有一些不应该存在的字符(00,01,FF),那么我不会收到此消息而不会出现错误。

这个任务似乎很简单,只需要输入文字

<order><data id="5" color="blue"/></order> 

进入msmq。

挖掘整个重要代码:

public static void Send()
    {
        using (message = new Message())
        {
            request req = new request("1", "blue");

                message.Recoverable = true;
                message.Body = req.ToString();
                message.Formatter = new BinaryMessageFormatter();
                using (msmq = new MessageQueue(@".\Private$\testrfid"))
                {
                    msmq.Formatter = new BinaryMessageFormatter();
                    msmq.Send(message, MessageQueueTransactionType.None);
                }
        }
    }

[Serializable]
public class request
{
    private readonly string _order;
    private readonly string _color;

    public request(string order, string color)
    {
        _order = order;
        _color = color;
    }
    public request()
    { }
    public string Order
    {
        get { return _order; }
    }
    public string Color
    {
        get { return _color; }
    }

    public override string ToString()
    {
        return string.Format(@"<request> <job order = ""{0}"" color = ""{1}"" /> </request>",_order,_color);
    }
}

您的问题根本不是很清楚。 只要使用BinaryMessageFormatter,就可以向MSMQ发送任何类型的消息。 这是一个例子:

string error = "Some error message I want to log";

using (MessageQueue MQ = new MessageQueue(@".\Private$\Your.Queue.Name"))
{
    BinaryMessageFormatter formatter = new BinaryMessageFormatter();
    System.Messaging.Message mqMessage = new System.Messaging.Message(error, formatter);
    MQ.Send(mqMessage, MessageQueueTransactionType.Single);
    MQ.Close();
}

我没有找到为什么Message.Body在传递给Body的字符串之前包含这些ascii字符的原因。 我只是直接填充BodyStream而不是Body,然后让它自己转换:

Message.BodyStream = new MemoryStream(Encoding.ASCII.GetBytes(string i want to put as Body))

然后,消息只是字符串而已。

您不需要可序列化的类将字符串发送到消息队列。

由于您使用的是BinaryMessageFormatter,因此必须首先使用文本编码器将字符串转换为字节数组,例如

message.Body = new UTF8Encoding().GetBytes(req.ToString());

我仅以UTF8为例,可以使用任何喜欢的编码。

然后,当您从队列中读取消息时,请记住使用相同的编码来获取字符串,例如

string myString = new UTF8Encoding().GetString(message.Body);

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM