C++ uses socket, ftp for file transfer, realizes the function of uploading and downloading files

C++ uses socket, ftp for file transfer, realizes the function of uploading and downloading files

Sockets need to be divided into server-side and client-side.

Service-Terminal

1 Declare and initialize a server (local) address structure

 
  sockaddr_in server_addr; 
  server_addr.sin_family = AF_INET; 
  server_addr.sin_addr.S_un.S_addr = INADDR_ANY; 
  server_addr.sin_port = htons(PORT); 

//2 Initialize the socket


  WSADATA wsaData; 
  WORD socketVersion = MAKEWORD(2, 0); 
  if(WSAStartup(socketVersion, &wsaData) != 0) 
  {
    
     
    printf("Init socket dll error!"); 
    exit(1); 
  } 

3 create socket

// 创建socket 
  SOCKET m_Socket = socket(AF_INET, SOCK_STREAM, 0); 
    if (SOCKET_ERROR == m_Socket) 
    {
    
     
      printf("Create Socket Error!"); 
    exit(1); 
    } 

4 binding monitor

//监听 
  if (SOCKET_ERROR == listen(m_Socket, 10)) 
  {
    
     
    printf("Server Listen Failed: %d", WSAGetLastError()); 
    exit(1); 
  } 

5 Read the information to determine whether the client needs to read the file or download the file

	char buffer[BUFFER_SIZE]; 
	memset(buffer, 0, BUFFER_SIZE); 
    if (recv(m_New_Socket, buffer, BUFFER_SIZE, 0) < 0) 
    {
    
     
      printf("Client Receive Data Failed!"); 
      break; 
    } 
	
	std::cout<<buffer<<endl;

Client

1Initialize the socket

// 初始化socket dll 
  WSADATA wsaData; 
  WORD socketVersion = MAKEWORD(2, 0); 
  if(WSAStartup(socketVersion, &wsaData) != 0) 
  {
    
     
    printf("Init socket dll error!"); 
    exit(1); 
  } 

2 Create a socket, specify the server

//创建socket 
	  SOCKET c_Socket = socket(AF_INET, SOCK_STREAM, 0); 
	  if (SOCKET_ERROR == c_Socket) 
	  {
    
     
		  printf("Create Socket Error!"); 
		  system("pause"); 
		  exit(1); 
	  } 
 
	  //指定服务端的地址 
	  sockaddr_in server_addr; 
	  server_addr.sin_family = AF_INET; 
	  server_addr.sin_addr.S_un.S_addr = inet_addr(SERVER_IP); 
	  server_addr.sin_port = htons(PORT); 

3 connect to the server

if (SOCKET_ERROR == connect(c_Socket, (LPSOCKADDR)&server_addr, sizeof(server_addr))) 
	  {
    
     
		  printf("Can Not Connect To Client IP!\n"); 
		  system("pause"); 
		  exit(1); 
	  } 

4 Ask the server for instructions, whether to upload or download.

		if(send(c_Socket, buffer, BUFFER_SIZE, 0) < 0) 
		{
    
     
			  printf("Send File Name Failed\n"); 
			  system("pause"); 
			  exit(1); 
		} 

Then the uploading and downloading process is similar to the reading and writing of local files.

Friends who need the source code can contact me. Other friends are also welcome to leave a message, exchange and learn

Insert picture description here

Guess you like

Origin blog.csdn.net/u011718690/article/details/114387114