介绍
在发展客户机/服务器应用程序,你经常需要发送到你的客户对象。对我们来说,最简单的方法程序员一起工作的对象将是从服务器得到整个对象,而不仅仅是一些性质。
一种方法是使用WCF或Web服务,它会给你一个类似的工具一整套系列化,能够完成这项任务,但这些技术的配套往往带来的开销和复杂性,以你的项目很多,你常常会如果不希望自己在做什么,只是发送和接收一个或多个对象。
与这一困境面前,我花了一些时间,如果这个解决方案看,我的目标是要找到一个非常容易,简单,明了的方法来创建服务器上的对象,序列化并发送回给客户端。安全性和互操作性并没有在这方面的忧虑,但他们可以稍后才能实现。这是为约束,它要快,而且要通过工作的基本HTTP协议。
我的解决方案是创建一个ASP.NET页面读取查询字符串,以确定哪些对象返回,创建对象,它的二进制序列,并返回一个二进制附件的客户端。客户端下载该文件使用 WebClient的() 类和反序列化回的对象。
在服务器和客户端共享类库包含的共同目标。起初,我实现了这个使用XML序列化,但发现它是相当缓慢的,但它也可以用来如果您需要的互操作性。
背景
记住,这不是唯一的方法to做到这一点,你也许可以做的WCF它使用一个自定义绑定或使用MTOM的,但我发现我的experience these methods被认为过于involved and added for simple projects不必要complexity 。
使用代码
在Web服务器上的网页加载,我们包括代码检查哪个对象的客户端请求,并返回一个二进制附件的序列化对象。
protected void Page_Load(object sender, EventArgs e)
{
// Check which object the client wants
if (Request.QueryString["op"] == "getdata")
{
// Create a new instance of the sample data object
var data = new SampleData();
data.moreData = 34343;
data.otherData = true;
data.SomeData = "fewoifjweofjwepo";
// Set content type and header
// octet-stream allow us to send binary data
// the file name here is irrelevant as it is
// not actually used by the client.
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition",
"attachment; filename=sampleData.bin");
// Serialzie the object and write it to the response stream
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(Response.OutputStream, data);
// Its important to end the response, overwise the other page content
// would be sent to the client.
Response.End();
}
在客户端,我们创建请求到服务器使用一个查询字符串,和反序列化的反应。
代码
1 // Create the url for the service, this could be stored in a configuration file
2 string url = "http://localhost/BinaryServiceSample/Default.aspx?op=getdata";
3 // Download the data to a byte array
4 // This data contains the actual object
5 var client = new WebClient();
6 byte[] result = client.DownloadData(url);
7 // Create a memory stream to stored the object
8 var mem = new MemoryStream(result);
9 var binaryFormatter = new BinaryFormatter();
10 var data = (SampleData)binaryFormatter.Deserialize(mem);
11 mem.Close();
12 // Write object to the console
13 Console.Write(data.ToString());
14 Console.ReadLine();
介绍