客户端->服务端—>客户端

客户端代码:

using (new OperationContextScope(client.InnerChannel))
           {
               Message request = Message.CreateMessage(OperationContext.Current.OutgoingMessageHeaders.MessageVersion,
                   "http://Microsoft.ServiceModel.Samples/IService1/Sum", values);

请求

Message reply = client.Sum(request);

获取应答结果:

int sum = reply.GetBody<int>();
               Console.WriteLine("Sum(1,2,3,4,5) = {0}", sum);

服务端代码:

public Message Sum(Message request)
       {
           int sum = 0;
           string text = "";

//获取消息的body节点

XmlReader body = request.GetReaderAtBodyContents();

while (body.Read())
           {
               text = body.ReadString().Trim();
               if (text.Length > 0)
               {
                   sum += Convert.ToInt32(text, CultureInfo.InvariantCulture);
               }
           }
           body.Close();

Message response = Message.CreateMessage(request.Version, "http://Microsoft.ServiceModel.Samples/IService1/SumResponse", sum);
           return response;

}

2.所有服务端代码

public Message Sum(Message request)
       {
           int sum = 0;
           string text = "";

//The body of the message contains a list of numbers which will be read directly using an XmlReader
           XmlReader body = request.GetReaderAtBodyContents();

while (body.Read())
           {
               text = body.ReadString().Trim();
               if (text.Length > 0)
               {
                   sum += Convert.ToInt32(text, CultureInfo.InvariantCulture);
               }
           }
           body.Close();

Message response = Message.CreateMessage(request.Version, "http://Microsoft.ServiceModel.Samples/IService1/SumResponse", sum);
           return response;

}

public Message GetFirst()
       {
           MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
           return Message.CreateMessage(ver, "http://Microsoft.ServiceModel.Samples/IService1/GetFirstResponse");
       }

public Message GetData()
       {
           Person p = new Person();
           p.name = "wang";
           p.age = 20;
           MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
           return Message.CreateMessage(ver, "http://Microsoft.ServiceModel.Samples/IService1/GetDataResponse", p);
       }

public Message GetDataStream()
       {
           FileStream stream = new FileStream(@"myfile.xml", FileMode.Open);
           XmlDictionaryReader xdr =
                  XmlDictionaryReader.CreateTextReader(stream,
                              new XmlDictionaryReaderQuotas());
           MessageVersion ver =
               OperationContext.Current.IncomingMessageVersion;
           return Message.CreateMessage(ver, "http://Microsoft.ServiceModel.Samples/IService1/GetDataStreamResponse", xdr);
       }

public Message GetDataFault()
       {
           FaultCode fc = new FaultCode("Receiver");
           MessageVersion ver = OperationContext.Current.IncomingMessageVersion;
           return Message.CreateMessage(ver, fc, "Bad data", "http://Microsoft.ServiceModel.Samples/IService1/GetDataFaultResponse");
       }

}

[DataContract(Namespace = "http://schemas.datacontract.org/2004/07/WcfServiceLibrary1")]
   public class Person
   {
       [DataMember]
       public string name;
       [DataMember]
       public int age;
   }

所有客户端代码:

int[] values = { 1, 2, 3, 4, 5 };

using (new OperationContextScope(client.InnerChannel))
            {
                Message request = Message.CreateMessage(OperationContext.Current.OutgoingMessageHeaders.MessageVersion,
                    "http://Microsoft.ServiceModel.Samples/IService1/Sum", values);

//Console.WriteLine(request.ToString());

Message reply = client.Sum(request);

//Console.WriteLine(reply.ToString());

int sum = reply.GetBody<int>();
                Console.WriteLine("Sum(1,2,3,4,5) = {0}", sum);

// demo 1
                Message Reply1 = client.GetFirst();
                Console.WriteLine(Reply1.ToString());

// demo 2
                Message reply2 = client.GetData();
                Console.WriteLine(reply2.ToString());
                Person p = reply2.GetBody<Person>();
                Console.WriteLine(p.name + "    " + p.age.ToString());

// demo 3
                Message reply3 = client.GetDataStream();
                Console.WriteLine(reply3.ToString());
                FileStream stream = new FileStream(@"c:\log.xml", FileMode.Create);
                XmlDictionaryWriter xdw =
                    XmlDictionaryWriter.CreateTextWriter(stream);
                //reply1.WriteBodyContents(xdw);
                //reply1.WriteBody(xdw);
                reply3.WriteMessage(xdw);
                xdw.Flush();

// demo 4
                try
                {
                    Message reply1 = client.GetDataFault();
                    Console.WriteLine(reply1.ToString());
                }
                catch (FaultException e)
                {
                    Console.WriteLine(e.ToString());
                }

Console.WriteLine("=====================Demo5========================");
                // demo 5
                Message reply5 = client.GetDataStream();
                //Copy the message to a buffer.
                MessageBuffer mb = reply5.CreateBufferedCopy(65536);

//Log to a file.
                FileStream stream1 = new FileStream(@"C:\log.xml", FileMode.Append);
                mb.WriteMessage(stream1);
                stream1.Flush();

Console.WriteLine("=====================Demo6========================");
                Message reply6 = client.GetData();
                Console.WriteLine(reply6.ToString());
                foreach (MessageHeaderInfo mhi in reply6.Headers)
                {
                    Console.WriteLine(mhi.Name);
                }

}

注意消息的版本

artech的文章

http://www.cnblogs.com/artech/archive/2009/07/27/1532438.html

源码:http://files.cnblogs.com/lzhp/WcfMessageService.zip

wcf中的Message类的更多相关文章

  1. WCF初探-22:WCF中使用Message类(上)

    前言 从我们学习WCF以来,就一直强调WCF是基于消息的通信机制.但是由于WCF给我们做了高级封装,以至于我们在使用WCF的时候很少了解到消息的内部机制.由于WCF的架构的可扩展性,针对一些特殊情况, ...

  2. WCF初探-23:WCF中使用Message类(下)

    前言 在上一篇WCF中使用Message类(上)中,文章介绍了WCF中使用Message类的基本知识和怎样创建消息,本文是承接上一篇文章,如果想要更好的阅读本文,请先阅读上一篇文章.在这篇文章中,我将 ...

  3. WCF初探-25:WCF中使用XmlSerializer类

    前言 在上一篇WCF序列化和反序列化中,文章介绍了WCF序列化和反序列化的机制,虽然WCF针对序列化提供了默认的DataContractSerializer序列化引擎,但是WCF还支持其他的序列化引擎 ...

  4. WCF基础之Message类

    客户端和服务端的通信都是通过接收和发送的Message实例建立起来的,大多数情况我们通过服务协定.数据协定和消息协定来构造传入和传出消息的. 一般什么时候使用Message类呢?不需要将消息序列化或者 ...

  5. WCF中,通过C#代码或App.config配置文件创建ServiceHost类

    C# static void Main(string[] args) { //创建宿主的基地址 Uri baseAddress = new Uri("http://localhost:808 ...

  6. 在 WCF 中使用高效的 BinaryFormatter 序列化

    本文将定义一个 WCF 终结点行为扩展,以在 WCF 中使用更高效的 BinaryFormatter 进行二进制序列化,并实现对是否使用传统二进制序列化功能的可配置. 介绍 实现步骤 使用方法 效果 ...

  7. WCF初探-28:WCF中的并发

    理解WCF中的并发机制 在对WCF并发机制进行理解时,必须对WCF初探-27:WCF中的实例化进行理解,因为WCF中的并发特点是伴随着服务实例上下文实现的.WCF的实例上下文模型可以通过Instanc ...

  8. WCF初探-27:WCF中的实例化

    理解WCF中的实例化机制 “实例化”是指对用户定义的服务对象以及与其相关的 InstanceContext 对象的生存期的控制.也就是说我们的客户端程序在调用服务端方法时,需要实例化一个服务端代理类对 ...

  9. WCF初探-26:WCF中的会话

    理解WCF中的会话机制 在WCF应用程序中,会话将一组消息相互关联,从而形成对话.会话”是在两个终结点之间发送的所有消息的一种相互关系.当某个服务协定指定它需要会话时,该协定会指定所有调用(即,支持调 ...

随机推荐

  1. 【Spring】SpringMVC之基于注解的实现SpringMVC+MySQL

    目录结构: contents structure [-] SprinigMVC是什么 SpringMVC工作原理 @Controller和@RequestMapping注解 @Controller注解 ...

  2. mongodb3.4 安装及用户名密码设置

    下载: https://www.mongodb.com/download-center?jmp=nav#community 1.解压  修改文件名为mongo3.2.5,执行命令如下: mv mong ...

  3. Python 文件 tell() 方法

    描述 Python 文件 tell() 方法返回文件的当前位置,即文件指针当前位置. 语法 tell() 方法语法如下: fileObject.tell() 参数 无 返回值 返回文件的当前位置. 实 ...

  4. how-to-convert-string-to-localdate

    Few Java examples show you how to convert a String to the new Java 8 Date API – java.time.LocalDate ...

  5. Java – Stream has already been operated upon or closed

    Java – Stream has already been operated upon or closed package com.mkyong.java8; import java.util.Ar ...

  6. flock防止crontab脚本周期内未执行完重复执行(转)

    如果某脚本要运行30分钟,可以在Crontab里把脚本间隔设为至少一小时来避免冲突.而比较糟的情况是可能该脚本在执行周期内没有完成,接着第二个脚本又开始运行了.如何确保只有一个脚本实例运行呢?一个好用 ...

  7. GitHub创始人:我如何放弃30万美元年薪创业

    GitHub创始人:我如何放弃30万美元年薪创业 本文摘自GitHub创始人Tom Preston Werner个人博客. 时间还在2007年,我一个人独坐旧金山的Zeke 体育酒吧内.其实我并不经常 ...

  8. android 判断点击的位置是不是在指定的view上

    private boolean inRangeOfView(View view, MotionEvent ev){ int[] location = new int[2]; view.getLocat ...

  9. Http Post 二进制通信

    客户端请求和接收(使用了httpclient4.3 和netty3.5) public static void httpPost11() { CloseableHttpClient httpClien ...

  10. Atitit gui界面ui技术发展史与未来趋势

    Atitit gui界面ui技术发展史与未来趋势 1. Gui技术的发展,从像素自绘到native控件体系,再到dsl h51 1.1. 编程语言的发展 从机器语言,汇编语言到本地native语言(c ...