结构文件:Astruct.cs //csc /t:library Astruct.cs using System; [Serializable] public struct Astruct{ public int seq;//结构的字段最好用public修饰 public char[] name; public ulong len; public char[] data; }
服务端: //compile with /r:Astruct.dll using System; using System.Net; using System.IO; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary;
class dropmulticast { public static void Main() { Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);//用tcp协议 IPEndPoint local = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0],8080);//监听8080端口 socket.Bind(local); socket.Listen(3);//允许3个客户连接 while (true) { Socket accept = socket.Accept();//接受连接的客户 BinaryFormatter bf; bf = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); Astruct ast = new Astruct(); ast.seq = 4; ast.name = new char[]{'n', 'a', 'm', 'e'}; ast.len = 4; ast.data = new char[]{'d', 'a', 't', 'a'}; bf.Serialize(stream, ast); byte[] buff = stream.ToArray(); accept.Send(buff, buff.Length, 0); accept.Close(); } } }
客户端: //compiler with /r:Astruct.dll using System; using System.Net; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary;
class Accept { public static void Main(String[] Args) { Socket client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); IPEndPoint remote = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0],8080); client.Connect(remote);//与服务端连接 NetworkStream stream = new NetworkStream(client);//取得服务端发送的数据 BinaryFormatter bf; bf = new BinaryFormatter(); Astruct reci = (Astruct) bf.Deserialize(stream);//反序列化数据 client.Close(); Console.WriteLine(reci); Console.Write("name is :"); Console.WriteLine(reci.name); Console.WriteLine("seq is :" + reci.seq); Console.WriteLine("len is :" + reci.len); Console.Write("data is :"); Console.WriteLine(reci.data); } }
---------------------------------------------------------------
序列化的类, 是用定义好的schema, 用xsd.exe生成一个类而产生的
序列化类xxxxxxx到xmlByte中
XmlSerializer serializer = new XmlSerializer(typeof(xxxxxxx)); MemoryStream ms = new MemoryStream(); Stream stream = ms; serializer.Serialize(stream,xxxxxxx); byte[] xmlByte = new Byte[stream.Length]; //指针归零 stream.Seek(0, SeekOrigin.Begin); stream.Read (xmlByte, 0, (int)stream.Length); stream.Close();
从xmlByte反序列化到对象obj中 XmlSerializer serializer = new XmlSerializer(typeof(xxxxxxx)); MemoryStream ms = new MemoryStream(); Stream stream = ms; //指针归零 stream.Seek(0, SeekOrigin.Begin); stream.Write(xmlByte, 0, (int)xmlByte.Length); //指针归零 stream.Seek(0, SeekOrigin.Begin); xxxxxxx obj = (xxxxxxx)serializer.Deserialize(stream); |