您好,登錄后才能下訂單哦!
一、 使用序列化類
序列化一個類,并通過網絡傳輸需要三步:
1、將要序列化的類創建成一個library對象。
2、編寫一個發送程序來創建要序列化類的實例,并發送。
3、編寫一個接收程序從流中讀取數據,并重新創建原來的序列化類。
① 編寫要序列化的類
每個要通過網絡傳輸數據的類必須在原代碼文件里使用[Serializable]標簽。這表明,類中所有的數據在傳輸時都將要被序列化。下面展示了如何創建一個可以序列化的類。
using System;
[Serializable] public class SerialEmployee { public int EmployeeID public string LastName;
public string FirstName;
public int YearsService;
public double Salary;
public SerialEmployee() { EmployeeID = 0;
LastName = null; FirstName = null;
YearsService = 0; Salary = 0.0; } }
為了使用該類來傳輸數據,必須現創建一個library文件: csc /t:library SerialEmployee.cs
② 編寫一個傳輸程序
創建數據類以后,可以創建一個程序來傳輸數據。可以使用BinaryFormatter和SoapFormatter類來序列化數據。
BinaryFormatter將數據序列化為二進制流。通常在實際數據中,增加一些信息,例如類名和版本號信息。
也可以使用SoapFormatter類使用XML格式來傳輸數據。使用XML的好處就是可以在任何系統和程序間傳遞數據。
第一必須創建一個流的實例來傳遞數據。可以是任何類型的流,包括FileStream,MemoryStream,NetworkStream。然后,可以創建一個序列化類,使用Serialize()方法來通過流對象傳遞數據:
Stream str = new FileStream( "testfile.bin", FileMode.Create, FileAccess.ReadWrite); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(str, data); Iformatter類創建了一個用來序列化的類的實例(BinaryFormatter或者SoapFormatter),使用Serialize()類來將數據序列化
using System;
using System.IO;
using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; class SoapTest { public static void Main() { SerialEmployee emp1 = new SerialEmployee();
SerialEmployee emp2 = new SerialEmployee();
emp1.EmployeeID = 1;
emp1.LastName = "Blum";
emp1.FirstName = "Katie Jane";
emp1.YearsService = 12;
emp1.Salary = 35000.50;
emp2.EmployeeID = 2;
emp2.LastName = "Blum";
emp2.FirstName = "Jessica";
emp2.YearsService = 9;
emp2.Salary = 23700.30;
Stream str = new FileStream("soaptest.xml", FileMode.Create, FileAccess.ReadWrite); IFormatter formatter = new SoapFormatter();
formatter.Serialize(str, emp1);
formatter.Serialize(str, emp2); str.Close(); } }
SoapFormatter類包含在System.Runtime.Serialization.Formatters.Soap命名空間,BinaryFormatter類包含在System.Runtime.Serialization.Formatters.Binary命名空間,Iformatter接口包含在System.Runtime.Serialization命名空間。
編譯代碼:CSC /r:SerialEmployee.dll SoapTest.cs
運行SoapTest.exe程序后,可以查看產生的soaptest.xml文件
1 Blum Katie Jane 12 35000.5 2 Blum Jessica 9 23700.3
查看soaptest.xml文件,我們可以發現在序列化類中SOAP是如何定義每個數據元素。一個值得注意的重要XML數據特點如下:
"http://schemas.microsoft.com/clr/assem/SerialEmployee%2C%20Version%3D0.Â0.0.0.%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull">
這里,XML中定義的數據使用了序列化數據類的實際類名。如果接收程序使用了另一個不同的類名,會和從流中讀取的XML數據不匹配。類不匹配,讀取將會失敗。
下面的代碼展示了如何序列化數據,將數據傳送到遠程系統。
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class BinaryDataSender { public static void Main() { SerialEmployee emp1 = new SerialEmployee();
SerialEmployee emp2 = new SerialEmployee();
emp1.EmployeeID = 1;
emp1.LastName = "Blum";
emp1.FirstName = "Katie Jane";
emp1.YearsService = 12;
emp1.Salary = 35000.50;
emp2.EmployeeID = 2;
emp2.LastName = "Blum";
emp2.FirstName = "Jessica";
emp2.YearsService = 9;
emp2.Salary = 23700.30;
TcpClient client = new TcpClient("127.0.0.1", 9050);
IFormatter formatter = new BinaryFormatter();
NetworkStream strm = client.GetStream();
formatter.Serialize(strm, emp1);
formatter.Serialize(strm, emp2);
strm.Close();
client.Close(); } }
因為BinaryFormatter和SoapFormatter類需要一個Stream對象來傳遞序列化的數據,所以要使用一個TCP Socket對象或者一個TcpClient對象來傳遞數據,不能直接使用UDP。
③編寫一個接收程序
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
class BinaryDataRcvr { public static void Main() { TcpListener server = new TcpListener(9050);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream strm = client.GetStream();
IFormatter formatter = new BinaryFormatter();
SerialEmployee emp1 = (SerialEmployee)formatter.Deserialize(strm); Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID); Console.WriteLine("emp1.LastName = {0}", emp1.LastName); Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName); Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService); Console.WriteLine("emp1.Salary = {0}\n", emp1.Salary); SerialEmployee emp2 = (SerialEmployee)formatter.Deserialize(strm); Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID); Console.WriteLine("emp2.LastName = {0}", emp2.LastName); Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName); Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService); Console.WriteLine("emp2.Salary = {0}", emp2.Salary); strm.Close(); server.Stop(); } } Winxp系統:c:\Windows c:\Windows\system32
二、 程序改進
在前面的程序中有一個假設:發送者的所有數據都被接收者接收。如果數據丟失,調用Deserialize()方法會發生錯誤。一個簡單的解決方法是將序列化數據放到MemoryStream對象中。MemoryStream對象將所有的序列化數據保存在內存中,可以很容易得到序列化數據的大小。當傳遞數據時,將數據大小和數據一起傳遞。
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
class BetterDataSender { public void SendData (NetworkStream strm, SerialEmployee emp) { IFormatter formatter = new SoapFormatter(); MemoryStream memstrm = new MemoryStream();
formatter.Serialize(memstrm, emp);
byte[] data = memstrm.GetBuffer();
int memsize = (int)memstrm.Length;
byte[] size = BitConverter.GetBytes(memsize);
strm.Write(size, 0, 4); strm.Write(data, 0, memsize); strm.Flush();
memstrm.Close(); } public BetterDataSender() { SerialEmployee emp1 = new SerialEmployee();
SerialEmployee emp2 = new SerialEmployee();
emp1.EmployeeID = 1; emp1.LastName = "Blum";
emp1.FirstName = "Katie Jane";
emp1.YearsService = 12;
emp1.Salary = 35000.50;
emp2.EmployeeID = 2;
emp2.LastName = "Blum";
emp2.FirstName = "Jessica";
emp2.YearsService = 9;
emp2.Salary = 23700.30;
TcpClient client = new TcpClient("127.0.0.1", 9050);
NetworkStream strm = client.GetStream();
SendData(strm, emp1);
SendData(strm, emp2);
strm.Close(); client.Close(); } public static void Main() { BetterDataSender bds = new BetterDataSender(); } } 接收數據程序如下:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Soap;
class BetterDataRcvr { private SerialEmployee RecvData (NetworkStream strm) { MemoryStream memstrm = new MemoryStream();
byte[] data = new byte[4]; int recv = strm.Read(data, 0, 4);
int size = BitConverter.ToInt32(data, 0);
int offset = 0;
while(size > 0) { data = new byte[1024];
recv = strm.Read(data, 0, size);
memstrm.Write(data, offset, recv);
offset += recv; size -= recv; } IFormatter formatter = new SoapFormatter(); memstrm.Position = 0;
SerialEmployee emp = (SerialEmployee)formatter.Deserialize(memstrm);
memstrm.Close();
return emp; } public BetterDataRcvr() { TcpListener server = new TcpListener(9050);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream strm = client.GetStream();
SerialEmployee emp1 = RecvData(strm);
Console.WriteLine("emp1.EmployeeID = {0}", emp1.EmployeeID); Console.WriteLine("emp1.LastName = {0}", emp1.LastName); Console.WriteLine("emp1.FirstName = {0}", emp1.FirstName); Console.WriteLine("emp1.YearsService = {0}", emp1.YearsService); Console.WriteLine("emp1.Salary = {0}\n", emp1.Salary); SerialEmployee emp2 = RecvData(strm); Console.WriteLine("emp2.EmployeeID = {0}", emp2.EmployeeID); Console.WriteLine("emp2.LastName = {0}", emp2.LastName); Console.WriteLine("emp2.FirstName = {0}", emp2.FirstName); Console.WriteLine("emp2.YearsService = {0}", emp2.YearsService); Console.WriteLine("emp2.Salary = {0}", emp2.Salary); strm.Close(); server.Stop(); } public static void Main() { BetterDataRcvr bdr = new BetterDataRcvr(); } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。