server.c
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024
//要实现的功能为:client 从 server 下载一个文件并保存到本地。
int main()
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKET server_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(1234);
bind(server_sock, (SOCKADDR *)&server_addr, sizeof(server_addr));
listen(server_sock, 0);
char Buff[Buff_len];
SOCKADDR client_addr;
memset(&client_addr, 0, sizeof(client_addr));
int nsize = sizeof(client_addr);
SOCKET ser_sock = accept(server_sock, &client_addr, &nsize);
int len = recv(ser_sock, Buff, Buff_len, 0);
printf("需要下载文件:%s\n", Buff);
FILE * fp = fopen(Buff, "rb");
if (fp == NULL)
{
printf("Open error!\n");
return 0;
}
printf("成功打开文件\n");
memset(Buff, 0, Buff_len);
printf("开始传输\n");
while (( len = fread(Buff, 1, Buff_len , fp)) > 0)
{
//printf("len = %d\n", len);
send(ser_sock, Buff, len, 0);
//printf("%s\n", Buff);
memset(Buff, 0, Buff_len);
}
shutdown(ser_sock, SD_SEND);
recv(ser_sock, Buff, Buff_len , 0);
printf("传输结束\n");
fclose(fp);
closesocket(ser_sock);
closesocket(server_sock);
WSACleanup();
return 0;
}
client.c
//要实现的功能为:client 从 server 下载一个文件并保存到本地。
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024
int main()
{
char Buff[Buff_len];
int len;
printf("请输入你要下载的文件名:");
scanf("%s", Buff);
len = strlen(Buff);
Buff[len] = '\0';
FILE * fp;
fp = fopen(Buff, "wb");
if (fp == NULL)
{
printf("open error!\n");
return 0;
}
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKET client_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(1234);
connect(client_sock, (SOCKADDR *)&server_addr, sizeof(server_addr));
send(client_sock, Buff, len+1,0);
printf("开始下载\n");
memset(Buff, 0, Buff_len);
while ((len = recv(client_sock, Buff, Buff_len, 0)) > 0) //一定要加括号,>优先级大于=
{
//printf("len = %d\n", len);
fwrite(Buff, 1, len, fp);
//printf("%s\n", Buff);
memset(Buff, 0, Buff_len);
}
printf("下载完毕\n");
fclose(fp);
closesocket(client_sock);
WSACleanup();
return 0;
}