socket编程技巧(1)tcp接收接口(变长数据定长数据)的编写实例

TCP读取定长数据接口的编写:

int readn(int fd,char*bp,size_t len)

{

  int cnt;

  int rc;

  

  cnt=len;

  while(cnt>0)

     {

    rc=recv(fd,bp,cnt,0);

           if(rc<0)//read error

          {

              if(errno==EINTR)

                  continue;

              return -1;//return error

          }

          if(0==rc)      //over?

          {

               return len-cnt;

          }

          bp+=rc;

          cnt-=rc;

     }

     return len;

}

TCP读取变长数据接口的编写(增加消息丢弃处理):

需要增加消息头,在消息头中说明数据的长度:

这里数据包的结构定义如下:

typedef struct

{

  u_int32_t recLen;

     char buf[128];

}packet;

int readvRec(int fd,char* bp,size_t len)//len:接收缓冲区的长度

{

    u_int32_t recLen;

    int rc;

    //retrieve the length of the record

    rc=readn(fd,&recLen,sizeof(u_int32_t));

    if(rc!=sizeof(u_int32_t))

   {

        return rc<0?-1:0;

   }

   recLen=ntohl(recLen);

   if(recLen>len)

   {

       //discard the record

       while(recLen>0)

      {

           rc=readn(fd,bp,len);

           if(rc!=len)

          {

               return rc<0?-1:0;

          }

          recLen-=len;

          if(len>recLen)

          {

              len=recLen;

          }

      }

      set_errno(EMSGSIZE);

      return -1;

   }

 //retrieve  the record

    rc=readn(fd,bp,recLen);

    if(rc!=len)

    {

         return rc<0?-1:0;

    }

    return rc;

}

原文地址:https://www.cnblogs.com/happy-pm/p/3821002.html