请教C#网络编程高手,小弟最近做一个C#的网络项目。网络服务端是用C++做的,已经做好。现在要用C#做一个客户端,需要用Socket发送和接收struct类型的数据包到服务器。小弟已在网上找过很多C#网络编程方面的资料,好像都是用Send(byte[],int,int)这样的方法发送。那位大哥大姐有解决办法或者其他解决方案???

解决方案 »

  1.   

    先把struct类型转换为byte[]再发送.有一个方法是专门将结构转换为byte[]的. 
      

  2.   

    参考一下这个:
    序列化:
    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;
      

  3.   

    同意楼上的,将class或struct完整的发送,可以进行串行化
      

  4.   

    1.讲对象序列化成byte[]
    2.将字节数组发送之。记住:你发送的永远都是byte[]
      

  5.   

    发送的就只能是byte[],就我所知应该没有其他什么方案的