server.c
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024
int main()
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKET server_sock = socket(AF_INET, SOCK_DGRAM, 0);
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));
char Buff[Buff_len];
SOCKADDR client_addr;
int nsize = sizeof(client_addr);
memset(&client_addr, 0, nsize);
int len = recvfrom(server_sock, Buff, Buff_len, 0, &client_addr, &nsize);
FILE *fp = fopen(Buff, "rb");
if (fp == NULL)
{
printf("open error\n");
closesocket(server_sock);
return 0;
}
printf("客户端需要下载文件:%s\n", Buff);
printf("开始传输\n");
memset(Buff, 0, Buff_len);
while ((len = fread(Buff,1,Buff_len,fp)) > 0)
{
printf("len = %d\n", len);
sendto(server_sock, Buff, len, 0, &client_addr, nsize);
printf("%s\n", Buff);
memset(Buff, 0, Buff_len);
}
printf("传输结束\n");
fclose(fp);
closesocket(server_sock);
WSACleanup();
return 0;
}
client.c
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
#define Buff_len 1024
int main()
{
char filename[64];
printf("请输入要下载的文件名:");
scanf("%s", filename);
int size = strlen(filename);
filename[size] = '\0';
FILE *fp = fopen(filename, "wb");
if (fp == NULL)
{
printf("open error\n");
return 0;
}
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKET client_sock = socket(AF_INET, SOCK_DGRAM, 0);
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);
sendto(client_sock, filename, size+1, 0, (SOCKADDR *)&server_addr, sizeof(server_addr));
printf("开始下载\n");
char Buff[Buff_len];
SOCKADDR recvfrom_addr;
memset(&recvfrom_addr, 0, sizeof(recvfrom_addr));
size = sizeof(recvfrom_addr);
int len;
while ((len = recvfrom(client_sock,Buff,Buff_len,0, (SOCKADDR *)&recvfrom_addr, &size)) > 0 )
{
printf("len = %d\n", len);
fwrite(Buff, 1, len, fp);
printf("%s\n", Buff);
memset(Buff, 0, Buff_len);
}
//这里有个问题,就是recvfrom()不会退出,总在阻塞,这个问题可以解决,好像蛮复杂的
//先放着,后面学多点知识在来解决
printf("下载完毕\n");
fclose(fp);
closesocket(client_sock);
WSACleanup();
return 0;
}