首页 > 代码库 > 自定义网络消息

自定义网络消息

#define MSG_HEAD_LEN     4



//消息头部结构
typedef struct tagMsg 
{
 //消息类型
 u16 type;    
 //消息体长度
 u16 length;
}TMsg;



void receive(SOCKET s)
{ 
 char buffer[1024*28];
 //CServMsg cMsg;
 u16 wRecvLen = 0 ;
 u16 wMsgLen = 0;
 u16 wRet = 0;
 
 while (TRUE)
 {
  if(wRecvLen < MSG_HEAD_LEN)
  {     
   wRet = recv(s, &(buffer[wRecvLen]), MSG_HEAD_LEN - wRecvLen, 0);
   wRecvLen += wRet;
   
   if ( wRecvLen == MSG_HEAD_LEN )
   {
    TMsg *ptMsg = (TMsg*)buffer;
    wMsgLen = ptMsg.length + MSG_HEAD_LEN;
   }
   //break;
  }
  else if( wRecvLen < wMsgLen )
  {
   wRet = recv(s, &(buffer[wRecvLen]), wMsgLen - wRecvLen, 0);
   wRecvLen += wRet;

   if ( wRecvLen == wMsgLen )
   {
    memset(buffer, 0, sizeof(buffer))
    wRecvLen = 0 ;
    wMsgLen = 0;
    wRet = 0;
   }     
  }
  else
  {
   //error
  }

   
 }
}