通过C#将消息放入Websphere MQ与手动放置相同消息的数据长度不同

时间:2011-08-11 17:30:44

标签: c# xml jms ibm-mq

MQMessage queueMessage = new MQMessage();
                queueMessage.WriteString(strInputMsg);
                queueMessage.Format = MQC.MQFMT_STRING;
                MQPutMessageOptions queuePutMessageOptions = new MQPutMessageOptions();
                Queue.Put(queueMessage, queuePutMessageOptions);

使用C#,使用上面的代码,当我将消息输入队列时,消息的数据长度为3600。

当我通过右键单击队列并选择Put Test Message选项手动将消息输入队列时,消息的数据长度为1799.

我真的很困惑为什么会这样。两种情况下的消息都是带声明的xml字符串。在Notepad ++中,有1811个字符,包括声明。当我在输入队列之前在调试器中查看消息时,消息将转换为xml,而不包含任何行或返回的支架。

我使用:

创建了xml字符串
//converts string message into xml by serializing it
 public string GetMessage(MyMessage messageInstance)
{

// Serialize the request
            XmlSerializer xsr = new XmlSerializer(typeof(MyMessage));
            MemoryStream memoryStream = new MemoryStream();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
            xsr.Serialize(xmlTextWriter, messageInstance);

            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            string XmlizedString = new UTF8Encoding().GetString((memoryStream.ToArray());


            // Encode the xml
            Encoding utf = Encoding.UTF8;
            byte[] utfBytes = utf.GetBytes(XmlizedString);

            // Load the document (XmlResolver is set to null to ingore DTD)
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = null;
            xmlDoc.LoadXml(utf.GetString(utfBytes));
            return utf.GetString(utfBytes);

我的C#实现中是否遗漏了添加额外字符的内容?

感谢。

1 个答案:

答案 0 :(得分:13)

正如@Matten所说,一个问题可能是字符编码。

CharacterSet属性的默认值为1200(UNICODE),WriteString转换为CharacterSet指定的代码页。

代码页1200是UTF-16 little-endian,因此每个字符可能会得到两个字节。 “Put Test Message”当然可能使用一些其他编码,每个字符使用一个字节用于公共字符。

假设3600和1799长度以字节计算,它们可以代表1800个UTF-16LE字符和1799个UTF-8字符(或1799个ASCII字符或1799个EBCDIC字符......)。

这仍然让我们的长度有一个字符差异。也许WriteString在字符串中包含一个终止的NULL字符?

你确定你信任Notepad ++给你的计数吗?如果Put Test Message将1799个字符放入一条消息中,那么您提供给它的数据中可能有1799个字符。

编辑:假设编码理论正确,您可以使用不同的编码缩短邮件。编码对特定消息的缩短程度取决于字符串的实际内容。

例如,您可以使用ASCII编码为每个字符获取一个字节。

MQMessage queueMessage = new MQMessage();
queueMessage.CharacterSet = 437;  // Set code page to ASCII

这会将您的消息缩短为1800字节如果 xml字符串中的所有字符都具有ASCII表示。

另一种方法是使用UTF-8编码。

MQMessage queueMessage = new MQMessage();
queueMessage.CharacterSet = 1208;  // Set code page to UTF-8

使用UTF-8的优点是(与ASCII不同)所有字符都有一个表示(对于'all'的某些值)。缺点是一些字符需要两个,三个甚至四个字节来表示它们。最常见的字符以一个字节编码,然后下一个最常见的字符以两个字节编码,依此类推。

在最好的情况下,UTF-8编码也会给你1800字节。在最坏的情况下,它会给你7200字节,但除非你使用像克林贡这样的东西,否则这似乎不太可能!