Click here to Skip to main content
15,504,830 members
Please Sign up or sign in to vote.
1.75/5 (4 votes)
See more:
I'm trying to send a files, with my server & client.
I just want to know how to send the file.
I tried few tutorials, but with one of them I got Debug error.
And the others, well its not easy to find very specific tutorial.
and i'm search the very easy one :D
So if you can just show me with the function "send" and "recv" without the all connection, its will be great xD
Thanks :)
Posted
Comments
[no name] 3-Aug-12 9:44am    
I got 456,000 results from a simple google search and you could not find anything?

Use an FTP library instead of coding this yourself.
Suppose you really want to do this yourself, then you need to start with the server. Run the server which will listen on a specific udp or tcp port.
Then you can create a client. In case of TCP it will first have to do a connect and then send data through the socket, in case of udp you can use sendto right away.
To do this correct is not so easy as it seams. That is why I suggest to use an FTP library unless you know what your are doing. Socket programming is advanced stuff. You either end up using a multithreaded application where the socket is being handled in a seperate thread, or using the select api on the socket and make the socket non blocking.
 
Share this answer
 
v2
Comments
Albert Holguin 3-Aug-12 9:52am    
I would not recommend using UDP at all for file transfers.
Philip Stuyck 3-Aug-12 9:59am    
For UDP there is already a protocol that supports file transferts too: TFTP, for TCP it is of course FTP. TFTP is also used in the industry, it is a acked protocol. Usually FTP should be faster because it is based on TCP which used a sliding window mechanism. So the sender does not wait for an ack of each packet like TFTP does.
A client is usually not so hard to program but especially a TCP server can be really complicated dependending on what you want to do. The reason is that a TCP server is usually able to handle multiple connections at once.
Albert Holguin 3-Aug-12 10:02am    
If you use UDP for file transfers, you end up duplicating TCP functionality at the application layer. Not worth it at all.
Philip Stuyck 3-Aug-12 10:10am    
Well not if you use a TFTP library, these exist too. But my first choice would be to use a FTP library because of the reliability and speed.
Albert Holguin 3-Aug-12 11:57am    
Well a library is doing that behind the scenes, but it's having to replicate the reliability of TCP nonetheless.
I'll show you the functional steps without code. You should be able to figure out the code.

0. Establish socket connection.
1. Read the input file in binary mode (for large files, only read in chunks).
2. Break up the file into chunks that fit into reasonable packet sizes.
3. Transmit packets.
4. On receive side, as you're receiving the binary data write it to a temporary file. Once all the chunks are received, close the file and name appropriately.

One thing you'll notice is... You'll need to know when a file transfer is about to begin, the name of the file, the file size (alternatively, transfer end). Hence, you'll need an application layer to your communications. FTP (as suggested in previous solution) is an application layer protocol that transfers files (hence the name, File Transfer Protocol). You could follow their guidelines, use a library, or just go ahead and code something yourself depending on your actual need or requirement.
 
Share this answer
 
Comments
Philip Stuyck 3-Aug-12 10:11am    
in case of winsock you need to initialise the winsock library first.
Hi Ido!
I think your send and receive functions should look like this (only client send function and server receive function)...
C++
// Client send function
nt Send(void* pvBuffer, int iStillToSend)
{
  int iRC = 0;
  int iSendStatus = 0;
  timeval SendTimeout;
  char *pBuffer = static_cast<char*>(pvBuffer);

  fd_set fds;

  FD_ZERO(&fds);
  FD_SET(Socket, &fds);

  // Set timeout
  SendTimeout.tv_sec  = 0;
  SendTimeout.tv_usec = 250000;              // 250 ms

  // As long as we need to send bytes...
  while(iStillToSend > 0)
  {
    iRC = select(0, NULL, &fds, NULL, &SendTimeout);

    // Timeout
    if(!iRC)
      return -1;

    // Error
    if(iRC < 0)
      return WSAGetLastError();

    // Send some bytes
    iSendStatus = send(Socket, pBuffer, iStillToSend, 0);   // Socket is of type 'SOCKET' and is the current connection socket

    // Error
    if(iSendStatus < 0)
      return WSAGetLastError();
    else
    {
      // Update buffer and counter
      iStillToSend -= iSendStatus;
      pBuffer += iSendStatus;
    }
  }

  return 0;
}


// Server receive function
int Receive(SOCKET Socket, void* pvBuffer, int iStillToReceive)
{
  int iRC = 0;
  int iReceiveStatus = 0;
  timeval ReceiveTimeout;
  char* pBuffer = static_cast<char*>(pvBuffer);

  // Set timeout
  ReceiveTimeout.tv_sec  = 0;
  ReceiveTimeout.tv_usec = 250000;             // 250 ms

  fd_set fds;

  FD_ZERO(&fds);
  FD_SET(Socket, &fds);

  // As long as we need to receive bytes...
  while(iStillToReceive > 0)
  {
    iRC = select(0, &fds, NULL, NULL, &ReceiveTimeout);

    // Timeout
    if(!iRC)
      return -1;

    // Error
    if(iRC < 0)
      return WSAGetLastError();

    // Receive some bytes
    iReceiveStatus = recv(Socket, pBuffer, iStillToReceive, 0);

    // Error
    if(iReceiveStatus < 0)
      return WSAGetLastError();
    else
    {
      // Update buffer and counter
      iStillToReceive -= iReceiveStatus;
      pBuffer += iReceiveStatus;
    }
  }

  return 0;
}


You can also see a great example here:

C++ Winsock Client To Server File Transfer - Made Easy[^]

and here:
http://www.daniweb.com/software-development/cpp/threads/295689/winsock-file-transfer-epic-slowness[^]
http://benshokati.blogspot.co.il/[^]
 
Share this answer
 
Comments
pasztorpisti 3-Aug-12 13:21pm    
I would add a few code related notes:
Why do you quit the send/recv loop if select() times out? I would just check a flag in ever X intervals if the user requested a cancel on the send. A select timeout isnt an error. Maybe you have a slow network that wasnt able to send your bytes in time.
You are using async socket management (select), in this case you should switch your socket to nonblocking and then handle EWOULDBLOCK errors after send()/recv() and ignore them. Maybe this isnt that important in this case where you have to handle only with one socket without the chance to cancel a send, but if you want to introduce a cancel mechanism or you handle more sockets its very important to swithc to nonblocking sockets!!! select() might wake up because some bytes have arrived to a socket, then you start reading it with recv() but the network system just found out that the crc of the received data is invalid, and with a blocking socket you might just start blocking on your socket with recv() and your other socket or the cancel flag started starving! This checksum stuff is an existing scenario, never encountered it but I read about it on msdn in a Qxxxxxx article.
EDIT: Another thing: if recv returns 0 it usually means that the peer closed the other side of the connection.
Y.Desros 4-Aug-12 2:04am    
Dear pasztorpisti! Your explanations are not relevant.
If you think that the code is given by another member(by the way, he gave a few examples) is not good enough, then as a counter argument bring your code! and then you can explain why you think that your example is better than an example given by another member of the forum
pasztorpisti 4-Aug-12 8:18am    
Dear Y.Desros!
Can you make it a bit more clear what is irrelevant in my comment please?
The posted code is similar to the patterns I use when its about networking and after fixing the bugs I mentioned it will be a suitable answer. Anyway, my explanation contains some human readable information too that might be harder to extract from code. Even if the code remains as it is, its good enough with my comment to help the OP to put togehter a solution.
Guys I know I'm noob xD
But i'll show you what i did with few tutorials.
And its creating the file but its not write its right ..

I tried to send a .txt file with some text in it ..
and its create the file, without the text in it..
here the functions:

C#
void FileRecive(char *Filename)
{
    FILE *File = fopen(Filename, "wb");

    // File size
    char Size[128];
    recvfrom(Socket, Size, 128, 0, (sockaddr*)&Addr, &Addrlen);
    Size[127] = '\0';
    int IntSize = atoi(Size);

    while(IntSize > 0)
    {
        char Buffer[1500];

        if(IntSize >= 1024)
        {
            recvfrom(Socket, Buffer, 1024, 0, (sockaddr*)&Addr, &Addrlen);
            fwrite(Buffer, 1024, 1, File);
        }
        else
        {
            recvfrom(Socket, Buffer, IntSize, 0, (sockaddr*)&Addr, &Addrlen);
            Buffer[IntSize] = '\0';
            fwrite(Buffer, 1024, 1, File);
        }

        IntSize -= 1024;
    }

    fclose(File);
}


C#
void SendFile()
{
    std::ifstream File;
    File.open("C:\\Text.txt", std::ios::in| std::ios::binary| std::ios::ate);
    int Size = (int)File.tellg();
    File.close();

    char FileSize[10];
    itoa(Size, FileSize, 10);

    // Send size
    sendto(Socket, FileSize, strlen(FileSize), 0, (sockaddr*)&Addr, sizeof(Addr));

    FILE *MyFile = fopen("C:\\Text.txt", "rb");

    while(Size > 0)
    {
        char Buffer[1500];

        if(Size >= 1024)
        {
            fread(Buffer, 1024, 1, MyFile);
            sendto(Socket, Buffer, 1024, 0, (sockaddr*)&Addr, sizeof(Addr));
        }
        else
        {
            fread(Buffer, 1024, 1, MyFile);
            Buffer[Size] = '\0';
            sendto(Socket, Buffer, Size, 0, (sockaddr*)&Addr, sizeof(Addr));
        }

        Size -= 1024;
    }

    fclose(MyFile);
}
 
Share this answer
 
Comments
pasztorpisti 3-Aug-12 13:24pm    
Sorry but I have to say that this is a totally bad solution. If you are using UDP then you have to put together a very complex piece of code that provides a reliable stream and it should contain something like this: http://en.wikipedia.org/wiki/TCP_congestion_avoidance_algorithm.
Instead of coding this whole UDP hell stuff you can use TCP that already contains these for you.
Albert Holguin 3-Aug-12 15:20pm    
He doesn't show how he established his socket, you're assuming its udp.
pasztorpisti 3-Aug-12 15:26pm    
You are right! :-)
Member 14841130 10-Jun-20 12:40pm    
Is this working??

From past three days I am facing an issue with one of my code which needs to transfer a file from server to code.
For this i am using TransmitFile function and before this trying to send the size of file and i used GetFileSize.
Once after the server connected with client, the server while sending the file size using send function. The server socket is disconnected.
Could anyone help me.
I need to transfer a zip file from server to 28 clients

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900