Windows TCP文件传输代码

windows socket编程
TCP文件传输部分

文件发送部分

//服务器发送文件,客户端接收文件
		char file_name[FILE_NAME_MAX_SIZE+1];
		memset(file_name, 0, FILE_NAME_MAX_SIZE+1);
		strncpy(file_name, buffer, strlen(buffer)>FILE_NAME_MAX_SIZE ? FILE_NAME_MAX_SIZE:strlen(buffer));
                printf("%s\n", file_name);
 
		FILE * fp = fopen(file_name, "rb");  //windows下是"rb",表示打开一个只读的二进制文件
		if (NULL == fp)
		{
			printf("File: %s Not Found\n", file_name);
		}
                else
		{
			memset(buffer, 0, BUFFER_SIZE);
			int length = 0;
 
			while ((length = fread(buffer, sizeof(char), BUFFER_SIZE, fp)) > 0)
			{
				if (send(m_New_Socket, buffer, length, 0) < 0)
				{
					printf("Send File: %s Failed\n", file_name);
					break;
				}
				memset(buffer, 0, BUFFER_SIZE);
			}
 
			fclose(fp);
			printf("File: %s Transfer Successful!\n", file_name);
		}
		closesocket(m_New_Socket);
	}

文件下载部分

//输入文件名
    char file_name[FILE_NAME_MAX_SIZE+1];
	memset(file_name, 0, FILE_NAME_MAX_SIZE+1);
	printf("Please Input File Name On Server: ");
	scanf("%s", &file_name);
 
	char buffer[BUFFER_SIZE];
	memset(buffer, 0, BUFFER_SIZE);
	strncpy(buffer, file_name, strlen(file_name)>BUFFER_SIZE ? BUFFER_SIZE:strlen(file_name));
 
	//向服务器发送文件名
	if(send(c_Socket, buffer, BUFFER_SIZE, 0) < 0)
	{
		printf("Send File Name Failed\n");
		system("pause");
		exit(1);
	}
 
	//打开文件,准备写入
	FILE * fp = fopen(file_name, "wb"); //windows下是"wb",表示打开一个只写的二进制文件
	if(NULL == fp)
	{
		printf("File: %s Can Not Open To Write\n", file_name);
		system("pause");
		exit(1);
	}
	else
	{
		memset(buffer, 0, BUFFER_SIZE);
		int length = 0;
		while ((length = recv(c_Socket, buffer, BUFFER_SIZE, 0)) > 0)
		{
			if (fwrite(buffer, sizeof(char), length, fp) < length)
			{
				printf("File: %s Write Failed\n", file_name);
				break;
			}
			memset(buffer, 0, BUFFER_SIZE);
		}
 
		printf("Receive File: %s From Server Successful!\n", file_name);
	}
 
	fclose(fp);
	closesocket(c_Socket);

你可能感兴趣的:(Windows TCP文件传输代码)