序列化:
1、定义结构
[Serializable()]
public struct structname
{
...
}
2、序列化
public static byte[] ObjectToByteA(object obj)
{
MemoryStream fs = new MemoryStream();
byte[] tmp = null;
try
{
// 序列化
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, obj);
tmp = fs.ToArray();
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
fs.Close();
}
return tmp;
}
3、反序列化
public static object ByteAToObject(byte[] ba)
{
MemoryStream fs = new MemoryStream();
object obj = null;
try
{
// 反序列化
fs = new MemoryStream(ba);
fs.Position = 0;
BinaryFormatter formatter = new BinaryFormatter();
obj = formatter.Deserialize(fs);
}
catch(Exception e)
{
MessageBox.Show(e.ToString(), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
fs.Close();
}
return obj;
}
4、using引用
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


以此为基础,可以完整实现Socket通信中结构或者对象的传输