首先我想定义这个问题
我将编写客户端和服务器之间的通信模块
客户做什么
-将Raport发送到服务器--->sendReport(Raport-Raport)
-从服务器-->getReport()方法获取特定的Raport
-获取可用raports的信息列表---->getRaportsInfo()
客户端类http://pastebin.com/344kfcbh
Server做什么
-从客户端获取请求(基于流中的第一个字节)
服务器类http://pastebin.com/wBwFPRpK
报表类
namespace OtherClasses
{
[Serializable]
public class Raport
{
public int day;
public int month;
public int year;
public Raport(int d, int m, int y)
{
day = d;
month = m;
year = y;
}
public void show()
{
Console.WriteLine("DAY=" + day + " MONTH=" + month + "YEAR=" + year);
}
}
}
干线中的某个位置
Server s = new Server();
s.acceptConnection();
Client c = new Client();
Raport r1 = new Raport(1, 1, 1);
c.connect("127.0.0.1");
c.sendReport(r1);
问题:显然,在从流中读取第一个字节后,我无法反序列化
我收到错误"输入流不是有效的二进制格式。"
SerializationException
读取第一个字节后,如何从流中反序列化
也许在类中包含命令?使用不同的类来指定所需的数据。类似于:
public enum RaportType {specific,general};
[Serializable]
public class RaportSpecific
{
public List<string> Data = new List<string>() { "One", "Two" };
}
[Serializable]
public class Raport
{
public RaportType RaportType = RaportType.specific;
public RaportSpecific Test = null; //new RaportSpecific();
服务器:
IFormatter formatter = new BinaryFormatter();
Raport receivedRaport = (Raport)formatter.Deserialize(n);
switch (receivedRaport.RaportType)
{
case RaportType.general:
Debug.WriteLine("You wanted to getRaportsInfo()");
/// to be implemented
break;
case RaportType.specific:
Debug.WriteLine("I've received your raport");
receivedRaport.show();
break;