序列化对象如何接收和传输

.NET 专栏收录该内容
2 篇文章 0 订阅
 

Itbaby

序列化对象如何接收和传输

结构文件: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);

    关闭本页|联系宝宝

      ©2004 - 2005 ItBaby 宝宝, 版权所有    

  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值