C ++: Use CSocket for File Transfer

Source: Internet
Author: User

There are two functions, one for the server, used for sending files, and the other for the client, used for receiving files, and can only be transferred to small files.

The following is the function code used for sending data to the server:

Void SendFile () {# define PORT 34000 // custom PORT
AfxSocketInit (NULL );
CSocket sockSrvr;
SockSrvr. Create (PORT); // Create a socket
SockSrvr. Listen (); // listening port
CSocket sockRecv;
SockSrvr. Accept (sockRecv );
CFile myFile; myFile. Open ("C: \ test. dat", // path of the file to be sent
CFile: modeRead | CFile: typeBinary );
Int myFileLength = myFile. GetLength ();
SockRecv. Send (& myFileLength, 4 );
Byte * data = new byte [myFileLength];
MyFile. Read (data, myFileLength );
SockRecv. Send (data, myFileLength );
MyFile. Close ();
Delete data;
SockRecv. Close ();
}
The following are functions used to accept client code:

Void GetFile () {# define PORT 34000 // custom PORT
AfxSocketInit (NULL );
CSocket sockClient;
SockClient. Create ();
// "127.0.0.1" is the IP to your server, same port
SockClient. Connect ("127.0.0.1", PORT );
Int dataLength;
SockClient. Receive (& dataLength, 4 );
Byte * data = new byte [dataLength];
SockClient. Receive (data, dataLength );
CFile destFile ("C: \ temp \ test. dat", // path of the saved file
CFile: modeCreate | CFile: modeWrite | CFile: typeBinary );
DestFile. Write (data, dataLength );
DestFile. Close ();
Delete data;
SockClient. Close ();
}
Note that because no judgment code is added, make sure that the SendFile () function runs first, and then run GetFile ()

Author: Li Mu Space"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.