Thread: How many datas when I send datas each time?

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    50

    How many datas when I send datas each time?

    Sorry ,maybe my englis is very poor.
    I create a socket using SOCK_STREAM,and I
    want to transfer a big file,and I know I
    must divide the big file,but I don't know
    how many datas to divide it?and what is
    the reason?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Well send() doesn't guarantee to send a whole block anyway (for a stream), so you need to deal with fragmentation on sending.

    Likewise for reading from a file, you may as well read in fixed sized blocks, rather than to try to allocate some xMB buffer you're only going to use once.

    Code:
      char buff[BUFSIZ];
      while ( (n=fread(buff,1,BUFSIZ,fp)) != 0 ) {
        char *p = buff;
        size_t  remainder = n;
        while ( remainder != 0 ) {
          n = send(sock,p,remainder,0);
          if ( n > 0 ) {
            // advance by the amount actually sent
            p += n;
            remainder -= n;
          } else if ( n == 0 ) {
            // remote disconnected
          } else {
            // error
          }
        }
      }
    One more thing, it's a good idea to send the size of the file first, so the receiver knows how much data to expect.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 0
    Last Post: 12-03-2011, 05:41 AM
  2. Ability to send and receive at the same time?
    By Martin_T in forum C Programming
    Replies: 1
    Last Post: 11-12-2009, 06:15 AM
  3. send signal every time input comes in on stdin
    By crs_zxf in forum C Programming
    Replies: 0
    Last Post: 11-04-2009, 07:38 AM
  4. Calling datas from another form?
    By Aga^^ in forum C# Programming
    Replies: 2
    Last Post: 02-06-2009, 02:17 AM
  5. Send/receive at the same time problem
    By nlight in forum C Programming
    Replies: 3
    Last Post: 05-12-2005, 06:06 PM