C#将二进制内容读入结构体,通过socket发送后读出结构体内容.

解决方案 »

  1.   

    http://topic.csdn.net/u/20071212/09/43435abe-df16-42cd-801b-64f29a12f6fc.html
    看这帖子里我的回复
      

  2.   

    将从socket接收的Byte[]转换为struct
    public object GetStruct(SocketHelper.CMDType cmdType, Byte[] _buffer)
    {
                        int headsize = SocketHelper.DataHeadSize;
                        IntPtr ptr = Marshal.AllocCoTaskMem(headsize);
                        Marshal.Copy(_buffer, 0, ptr, headsize);
                        _struct = Marshal.PtrToStructure(ptr, typeof(SocketHelper.DataHeader));
    }
        public class SocketHelper
        {
            public const int DataHeadSize=11;        public struct DataHeader
            {
                public DataHeader(int str)
                {
                    Mark = "ABCDEFGHIJ".ToCharArray();
                    nCmdType = '0';
                }
                public char[] Mark;//10
                public char nCmdType;
            };
        }
      

  3.   

    测试没反应
    结构体
    public struct My_Test
        {
            public string Ip;
            public string Port;
            public string str_Msg;
        }客户端
    发送事件
     Stream str = new NetworkStream(sok);
     My_Test myobj = new My_Test();
     myobj.Ip = this.textBox1.Text;
     myobj.Port = this.textBox2.Text;
     myobj.str_Msg = this.richTextBox2.Text;
     int size = Marshal.SizeOf(myobj);
     IntPtr buffer = Marshal.AllocHGlobal(size);
     Marshal.StructureToPtr(myobj, buffer, true);
     byte[] sendbyte = new byte[size];
     Marshal.Copy(buffer, sendbyte, 0, size);
     IFormatter formatter = new BinaryFormatter();
     formatter.Serialize(str, myobj);
     sok.Send(sendbyte);
     Marshal.FreeHGlobal(buffer);   服务端
    int size = Marshal.SizeOf(myobj);
    IntPtr buffer = Marshal.AllocHGlobal(size);
    byte[] byt = new byte[size];
    Marshal.Copy(byt, 0, buffer, size);
    string strip=((My_Test)Marshal.PtrToStructure(buffer, myobj.GetType())).Ip;
    string strmsg = ((My_Test)Marshal.PtrToStructure(buffer, myobj.GetType())).str_Msg;
    newsok.Receive(byt, byt.Length, 0);
    string str = "";
    //委托将数据显示到文本框
    GetControl getcon = new GetControl(GetStr);
    this.BeginInvoke(getcon, new object[] { strmsg });
    Marshal.FreeHGlobal(buffer);