繁体   English   中英

从C#读取WCF MSMQ消息

[英]Read WCF MSMQ Message from C#

我使用WCF客户端向WCF服务发送msmq消息,在WCF服务处理msmq消息之前,我想检查消息的正文。
在检查了msmq消息体的内容后,我得到了以下结果。
在此输入图像描述
但是,我没能得到确切的字符串。
以下是WCF服务的定义

    [ServiceContract]
public interface IMSMQService
{

    [OperationContract(IsOneWay = true)]       

    void ShowMessage(string msg);
}

我使用下面的方法来检索邮件正文,并输出为空,如果我在ms上添加监视,我可以得到

“\\ 0 \\ U0001 \\ 0 \\ U0001 \\ U0004 \\ U0002(net.msmq:// VDI-V-tazho /私人/ TestQueue \\ U0003 \\ AV \\ U0002符\\ v \\ u0001s \\ U0004符\\ v \\ u0001a \\ u0006V \\ BD \\ n \\ u001e \\0 + http://tempuri.org/IMSMQService/ShowMessage@ \\ u0017VsDebuggerCausalityData \\ bAhttp://schemas.microsoft.com/vstudio/diagnostics/servicemodelsink < ϣ-lN FoJ 0 U \\ u0006 \\“\\ 0 \\ 0 \\ 0 \\ 0 \\ u0017 \\ 0i8CI \\ 7 ^ QA \\ u0012w} \\为fA \\ u000f \\ rޮPE \\ 0 \\吨\\ 0 \\ 0D \\˚F\\ u001e \\ 0(net.msmq:// VDI-v-tazho /私人/ TestQueue \\ u0001V \\ u000e @ \\ vShowMessage \\ b \\ u0013http://tempuri.org/@ \\ u0003msg \\ u0004test \\ U0001 \\ U0001 \\ U0001"

                //message.Formatter = new XmlMessageFormatter(new String[] { });
            //StreamReader sr = new StreamReader(message.BodyStream);
            string ms = "";
            //while (sr.Peek() >= 0)
            //{
            //    ms += sr.ReadLine();
            //}
            message.Formatter = new ActiveXMessageFormatter();
            string result = System.Text.Encoding.UTF8.GetString(message.Body as byte[]);
            StreamReader reader = new StreamReader(message.BodyStream);

            ms = reader.ReadToEnd();
            MessageBox.Show(ms);

我得到了以下代码来实现我的要求。

private void MSMQStringBody_Click(object sender, EventArgs e)
{
    System.Messaging.MessageQueue[] queueList = System.Messaging.MessageQueue.GetPrivateQueuesByMachine(Environment.MachineName);
    MessageQueue myQueue = queueList[1];
    List<System.Messaging.Message> messages = myQueue.GetAllMessages().ToList();
    foreach (System.Messaging.Message message in messages)
    {
        System.Xml.XmlDocument result = ConvertToXMLDoc(message);
        MessageBox.Show(result.InnerText);
    }

}
public System.Xml.XmlDocument ConvertToXMLDoc(System.Messaging.Message msg)
{
    byte[] buffer = new byte[msg.BodyStream.Length];
    msg.BodyStream.Read(buffer, 0, (int)msg.BodyStream.Length);
    int envelopeStart = FindEnvolopeStart(buffer);
    System.IO.MemoryStream stream = new System.IO.MemoryStream(buffer, envelopeStart, buffer.Length - envelopeStart);
    System.ServiceModel.Channels.BinaryMessageEncodingBindingElement elm = new System.ServiceModel.Channels.BinaryMessageEncodingBindingElement();
    System.ServiceModel.Channels.Message msg1 = elm.CreateMessageEncoderFactory().Encoder.ReadMessage(stream, Int32.MaxValue);
    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
    doc.Load(msg1.GetReaderAtBodyContents());
    msg.BodyStream.Position = 0;
    return doc;
}
private int FindEnvolopeStart(byte[] stream)
{
    int i = 0;
    byte prevByte = stream[i];
    byte curByte = (byte)0;
    for (i = 0; i < stream.Length; i++)
    {
        curByte = stream[i];
        if (curByte == (byte)0x02 &&
        prevByte == (byte)0x56)
            break;
        prevByte = curByte;
    }
    return i - 1;
}

当您向/从MSMQ发送/检索消息正文时,您应该使用相同的“类型”。 请参阅下面的通用类型“T”。 T可以是您的任何自定义类。

    public T GetQueueMessage()
    {
        Message message = queue.Receive(new TimeSpan(0, 0, 0, 1, 0));
        return (T)message.Body;
    }

    public void InsertQueueMessage(T message)
    {
        using (Message msg = new Message((object)message))
        {
            queue.Send(msg, MessageQueueTransactionType.Single);
        }
    }

我知道问题是C#代码,但我在这里包括Powershell脚本,对于那些喜欢使用shell快速检查MSMQ内容的人。 使用Edward的代码我也使用Powershell进行了这项工作,如果有人正在寻找一个脚本,可以使用协议绑定NetMsmqbinding或NetMsmqIntegrationBinding来提取这些作为有效负载发送的WCF消息到端点的WCF服务。

而不是使用Int32.MaxValue,我使用了另一个大整数值,我知道在大多数情况下就足够了。 很高兴知道顺便找到Soap Envelope背后的逻辑。

这是Powershell脚本:

[System.Reflection.Assembly]::LoadWithPartialName("System.Messaging") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.Xml") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.ServiceModel") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("System.IO") | Out-Null


$queuePath = ".\private$\demoqueue4"

Write-Host "Powershell MSMQ queue WCF inspector v0.1. Inspecting queue contents of the queue: $queuePath"
Write-Host ""


Run-MainDemoIterateMsmq $queuePath



Function Get-XmlFromWcfMessage([System.Messaging.Message] $msg) {

    $doc = New-Object System.Xml.XmlDocument;
    $messageLength = [int] $msg.BodyStream.Length


    $buffer = New-Object byte[] $messageLength


    $msg.BodyStream.Read($buffer, 0, $messageLength)

    $envelopeStart = Find-SoapEnvelopeStart($buffer)

    $envelopeStart = $envelopeStart - 0

    $envelopeLength = $($buffer.Length - $envelopeStart)
    #Write-Host $envelopeStart


    $stream = New-Object System.IO.MemoryStream($buffer, $envelopeStart, $envelopeLength)

    $elm = New-Object System.ServiceModel.Channels.BinaryMessageEncodingBindingElement
    $elm.ReaderQuotas.MaxStringContentLength = 10000000
    $elm.ReaderQuotas.MaxBytesPerRead = 10000000


    $msg1 = $elm.CreateMessageEncoderFactory().Encoder.ReadMessage($stream, 10000000);

    $doc.Load($msg1.GetReaderAtBodyContents());

    $msg.BodyStream.Position = 0;



    return $doc;
}

Function Find-SoapEnvelopeStart([byte[]] $stream)
{
    $i = 0;
    $j = 0;
    $prevByte = $stream[$i];
    $curByte = [byte]$j;
    for ($i = 0; $i -lt $stream.Length; $i++)
    {
        $curByte = $stream[$i];
        if ($curByte -eq [byte] 0x02 -and $prevByte -eq [byte] 0x56) {
            break;
        }
        $prevByte = $curByte;
    }
    return $i - 1;
}


Function Run-MainDemoIterateMsmq([string] $queuePath) {

$queue = New-Object System.Messaging.MessageQueue $queuePath

foreach ($message in $queue.GetAllMessages()){
  $xmlDoc = Get-XmlFromWcfMessage $message 
  Write-Host $xmlDoc.OuterXml
 } 


}

然后输出可能如下所示:

    <SendMessage xmlns="http://tempuri.org/"><message>this is another test!</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>why hello srmp</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>test</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>my message to msmq</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>This is a new message!</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>Another message to MSMQ! </message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>another test here</message></SendMessage>
    <SendMessage xmlns="http://tempuri.org/"><message>This is a test message that will be sent using NetMsmqBinding. </message></SendMessage>
    <SendMessageDataContract xmlns="http://tempuri.org/"><message xmlns:b="http://schemas.datacontract.org/2004/07/WcfDemoNetMsmqBinding.Host" xmlns:i="http://www.w3.org/2001
    /XMLSchema-instance"><b:BoolValue>true</b:BoolValue><b:StringValue>This is a test of a stringvalue for a CompositeType</b:StringValue></message></SendMessageDataContract>

暂无
暂无

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

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