home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.protocols.tcp-ip      TCP and IP network protocols.      14,669 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 13,241 of 14,669   
   Jorgen Grahn to zhangyefei.yefei@gmail.com   
   Re: how to use MSG_PEEK flag   
   02 Dec 09 12:41:30   
   
   185baab0   
   From: grahn+nntp@snipabacken.se   
      
   On Wed, 2009-12-02, zhangyefei.yefei@gmail.com wrote:   
   > hi all,   
   >    If i want to read N bytes from a socket  ,can i do it like this:   
   >    1) first ,i  call recv with MSG_PEE flag to confirm  whether having   
   >        N bytes available.   
   >        repeat it untill having N bytes available.   
   >    2)  then, call read once (and just once ) to receive N bytes.   
   >   
   > the following is my codes:   
   > /*   
   > return value:   
   > 0 : got len bytes in buf successfully   
   > -1: error when receiving data from socket   
   > */   
   > int myrcv(int fd,int len,char* buf)   
   > {   
   >         int n=0;   
   >         //peeking whether having n bytes available   
   >         while (n          {   
   >                 n=recv(fd,buf,len,MSG_PEEK);   
   >                 if(n         }   
   >         n=read(fd,buf,len);   
   >         if(n!=len)   
   >         {   
   >                 return -1;   
   >         }   
   >         return 0;   
   > }   
   >   
   > are there bugs in my codes ? or anything wrong ?   
   > thank you .   
      
   Why do you want to use MSG_PEEK?  It will not make the code faster;   
   the sleep() can make it thousands of times slower.  If you are going   
   to sleep, you might as well sleep in a recv() call.   
      
   Since you do not want to return until you have len bytes or an error,   
   why not just call recv() repeatedly, adding to your buf until it is   
   full?  I assume this is a TCP socket in blocking mode.   
      
      xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx   
      buf                                        buf+len   
      ............   
         read     ......   
                   read .......................   
   		              read          ..   
   			                    read, and done!   
      
   /Jorgen   
      
   --   
     // Jorgen Grahn    O  o   .   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca