2013-08-23 54 views
2

我想使MSMQ消息,這將有文字例如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); 
    } 
} 
+1

Downvoter:這是不禮貌的反對票沒有留下評論。 –

+0

事實上,我編輯過這個問題。原來的形式非常模糊,所以可能多數民衆贊成在爲什麼。 –

+0

當使用'BinaryMessageFormatter'時,你不應該關心它看起來像什麼。雖然您可能試圖將其序列化爲XML,但「BinaryMessageFormatter」沒有做出這樣的保證。重要的是,您使用相同的格式化程序來讀取消息,就像您寫消息一樣。使用該格式化程序時,它的意思不是人類可讀的。 – tcarvin

回答

0

我一直沒有找到原因Message.Body包含我傳遞給車身的字符串之前,這些ASCII字符。我只是直接填充BodyStream而不是Body,並讓它自己轉換:

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

然後,消息只是沒有別的字符串。

+0

我來這裏尋找一種強制執行消息格式的方式,但它似乎不可能,反正也不是分佈式的。現在,關於您看到的額外字節,它們可能是BOM(字節順序標記),它是編碼的產物。例如,UTF-8應該加上'EF BB BF'(''''),所以如果你將一個UTF-8字節數組解碼爲ASCII,你會在結果的開頭得到''。儘管我在'00 01 FF'上找不到任何東西,但我確信它們代表了BOM。請閱讀[BOM列表](https://en.wikipedia.org/wiki/Byte_order_mark)。 – Heki

1

你的問題不是很清楚,在所有;只要您使用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(); 
} 
-1

您不需要可序列化的類將字符串發送到消息隊列。

由於您使用的是BinaryMessageFormatter,因此必須先使用文本編碼器將字符串轉換爲字節數組,例如,

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

我只是用UTF8作爲例子,你可以使用任何你喜歡的編碼。

然後,當您從隊列中讀取消息時,請記住使用相同的編碼將字符串返回到例如

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

希望這有助於