【问题标题】:C# Client Server Module , Serialization Does not workC#客户端服务器模块,序列化不起作用
【发布时间】:2013-11-18 17:49:59
【问题描述】:

首先我想定义问题。
我要编写客户端和服务器之间的通信模块。
客户做什么?
- 将 Raport 发送到服务器 ---> sendReport(Raport raport)
- 从服务器获取特定的报告 --> getReport() 方法
- 获取有关可用报告的信息列表 ----> getRaportsInfo()

客户端类http://pastebin.com/344kfcbh

服务器是做什么的?
- 从客户端获取请求(基于流中的第一个字节)
服务器类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
如何在读取第一个字节后从流中反序列化

【问题讨论】:

  • 这个 Raport 类是否被复制到两个项目中?还是在两个项目都引用的库 (dll) 中?
  • 顺便说一句 - BinaryWriter 和原始流的使用令人困惑,我认为这里不正确:您正在执行“在 writer 上写入 3”、“serialize to stream”、“flush writer”。应该是“write 3 on writer”、“flush writer”、“serialize to stream”。或者更好的是:“write 3 to stream, serialize to stream”(失去 writer)
  • 补充点:你写的 3 不是一个字节。然而你读起来好像它是一样的。
  • 正如马克所说 w.Write((byte)3);它有效。

标签: c# serialization stream network-programming client


【解决方案1】:

也许在类中包含命令?使用不同的类来指定所需的数据。比如:

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;

【讨论】:

    猜你喜欢
    • 2015-12-09
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 2012-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多