我要做一款游戏,主机启动后采用广播的形式发送主机的头像和用户名报文,于是就把这个含有主机的头像和用户名报文(封装成HostInfo类)用Serialize进行序列化,然后客户端接收广播报文后,进行反序列化(主要代码见下方),可是接收到的报文中的用户名内容可以正常解码,而头像FileStream却是空的,这是为什么?
public static byte[] Serialize(object obj)
{
byte[] r = null;
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
try
{
binaryFormatter.Serialize(ms, obj);
r = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
int c = ms.Read(r, 0, r.Length);
}
catch
{ }
}
return r;
}
public static T Deserialize<T>(byte[] buf) where T : class
{
T r = default(T);
BinaryFormatter binaryFormatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
ms.Write(buf, 0, buf.Length);
ms.Seek(0, SeekOrigin.Begin);
try
{
r = binaryFormatter.Deserialize(ms) as T;
}
catch
{ }
}
return r;
}
头像和用户名报文我单独封装成一个HostInfo类,然后将用户名进行序列化,用户头像是FileStream,使用 [NonSerialized] 不对它进行序列化(因为调试时发现FileStream序列化后广播报文发不出去)。
[Serializable]
public class HostInfo
{
/// <summary>
/// 主机用户名
/// </summary>
public string hostName;
/// <summary>
/// 主机用户头像
/// </summary>
[NonSerialized] public FileStream fsHeadPortrait;
}