客户端代码
   struct OpenPoint
   {
short Game_Function;
char  UserName[20];
int   mOpenPoint;
   };
   
   CSocket m_pSocket;
   OpenPoint m_OpenPoint;
   
   char* CharUserName="daf"
   ZeroMemory(&m_OpenPoint,sizeof(OpenPoint));
   m_OpenPoint.Game_Function=2;
   strcpy(m_OpenPoint.UserName,CharUserName);
   m_OpenPoint.UserName[strlen(CharUserName)]='\0';
   m_OpenPoint.mOpenPoint=100;   
   int send = 0;
   while(send<sizeof(OpenPoint))
    {
     int nCharSend=m_pSocket->Send((void*)(&m_OpenPoint+send),sizeof(OpenPoint)-send,0);
     send+=nCharSend;
    }
服务器代码   struct OpenPoint
   {
char  UserName[20];
int  mOpenPoint;
   };
  
   CSocket m_pServerSocket;
   OpenPoint m_OpenPoint;
   short temp;
  m_pServerSocket->Receive(&temp,sizeof(short),0);
  switch(temp)
  {
    
    case 0:
{
     break;
}   case 2:
{
  ZeroMemory(&m_OpenPoint,sizeof(OpenPoint));
          int receive = 0;
          while(receive<sizeof(OpenPoint))
 {
          int nCharSend=m_pServerSocket->Receive((void*)(&m_OpenPoint+receive),sizeof(OpenPoint)-receive,0);
            receive+=nCharSend;
}
  }  为什么接收到的m_pServerSocket.mOpenPoint=6553600(本来应该是100)而m_pServerSocket.UserName则正常?

解决方案 »

  1.   

    这是一个关于使用CSocket传输struct数据类型的非常经典的错误.错误原因在于结构(struct)中有数据对齐属性!
    关于这一点可以用sizeof(OpenPoint)来确认, 返回值不是你期望的!
    不同的机器对于对齐属性有不同的设置,所以不进行1byte对齐而在不同的机器间传递结构一定会有多余的填充数据扰乱传输结果...关于控制结构(struct)对齐属性有多种方法,最简单的方法如下:1)open menu "project\settings..."
    2)select "C\C++" tab
    3)select "Code generation" category
    4)select "1 Byte" from "struct member alignment" list
    5)rebuild all projects and run again.
      

  2.   

    没见有什么错,你CASE 2,BREAK了没有?
      

  3.   

    struct OpenPoint
       {
    short Game_Function; //和USERNAME前2字节共占4字节
    char  UserName[20];  //剩下18字节,占5个四字节
    int   mOpenPoint;    //占一个4字节.
       };
       struct OpenPoint
       {
    char  UserName[20];  //占5个四字节
    int  mOpenPoint;     //占一个四字节
       };解决方法:short Game_Function改为int类型就 可以 了.