在Server和Client分别定义序列化的Struct,我建议将序列化的Struct改为序列化的Class,这样就肯定能在Server和Client间传输了

解决方案 »

  1.   

    看看读到的stream有没有问题,估计是你的NetworkStream 的用法有点问题server端的代码呢?
      

  2.   

    using System;
    using System.Net;
    using System.IO;
    using System.Net.Sockets;
    using System.Runtime.Serialization.Formatters.Binary;
    using System.Text ;namespace Server
    {
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    class dropmulticast
    {
    [Serializable]
    public struct Astruct
    {
    public int seq;//结构的字段最好用public修饰
    public char[] name;
    public ulong len;
    public char[] data;
    public byte[] byt ;
    }
    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],8070);//监听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();
    }
    //Console.ReadLine() ;
    }
    }以上是我的Server端代码
      

  3.   

    // 用 Marshal 傳回類別的 Unmanaged 大小 (以位元組為單位)
    int size = Marshal.SizeOf(pAskConnect);
    // 使用 GlobalAlloc 配置記憶體區塊
    System.IntPtr ptr = Marshal.AllocHGlobal(size);
    // 從 Managed 物件封送處理資料到 Unmanaged 記憶體區塊
    Marshal.StructureToPtr(pAskConnect, ptr,true);
    byte[] ba=new byte[size];
    // 從 Managed 陣列將資料複製到 Unmanaged 記憶體指標
    Marshal.Copy(ptr, ba, 0, ba.Length );
      

  4.   

    你确定在client和server端都有这个结构定义吗?
    你为什么把//[Serializable]去掉了,不声明为可序列化的东西,怎么事先serialize呢?加上就好了,不过可能要改为class的。
      

  5.   

    我又测试了一下,直接用struct就可以了,不用改为class。
    至少我这里能正确执行。