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"