本程序转自腾讯课堂里面的《C++之网络编程》视频教程里的。地址为 https://ke.qq.com/course/141506#term_id=100159728
服务器端:
#include<stdio.h>
#include<string.h>
#include<WinSock2.h>
#include<Windows.h>
#include<iostream>
#pragma comment(lib,"WS2_32.lib")
#define MAX_BUF 65536
using namespace std;
int main()
{
//初始化版本号
WSADATA wsaData;
int ret=WSAStartup(MAKEWORD(2,2),&wsaData);
if(ret!=0)
{
cout<<"wsastarup error"<<endl;
return 0;
}
//建立套接字
SOCKET s;
s=socket(AF_INET,SOCK_DGRAM,0);
if(s==INVALID_SOCKET)
{
cout<<"socket error"<<endl;
WSACleanup();
return 0;
}
//定义一个地址,并进行绑定
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(5000);
sin.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
//绑定地址
int r=bind(s,(sockaddr*)&sin,sizeof(sin));
if(r==SOCKET_ERROR)
{
cout<<"bind error"<<endl;
closesocket(s);
WSACleanup();
return 0;
}
//接收缓存区
char recvbuf[MAX_BUF];
//初始化缓存区
memset(recvbuf,0,MAX_BUF);
//定义一个地址结构
sockaddr_in addr;
int addrlen=sizeof(addr);
//输入文件的路径
char path[100]={"0"};
cout<<"请输入文件的路径:(例如D:\\1.txt)"<<endl;
cin>>path;
//打开文件
FILE *fp;
fopen_s(&fp,path,"wb");
if(!fp)
{
cout<<"文件打开失败"<<endl;
return 0;
}
else
{
cout<<"文件已经打开,等待传输......"<<endl;
}
while (true)
{
//接收
memset(recvbuf,0,MAX_BUF);
int rBye=recvfrom(s,recvbuf,MAX_BUF,0,(sockaddr*)&addr,&addrlen);
//接收失败
if(rBye==SOCKET_ERROR)
{
cout<<"recvfrom error"<<WSAGetLastError()<<endl;
closesocket(s);
WSACleanup();
return 0;
}
//接收成功
fwrite(recvbuf,1,1024,fp);
fclose(fp);
}
closesocket(s);
WSACleanup();
return 0;
}
客户端:
本程序转自腾讯课堂里面的《C++之网络编程》视频教程里的。地址为 https://ke.qq.com/course/141506#term_id=100159728
#include<stdio.h>
#include<string.h>
#include<WinSock2.h>
#include<iostream>
#include<Windows.h>
#pragma comment(lib,"WS2_32.lib")
using namespace std;
int main()
{
//初始化版本号
WSADATA wsaData;
int ret=WSAStartup(MAKEWORD(2,2),&wsaData);
if(ret!=0)
{
cout<<"wsastarup error"<<endl;
return 0;
}
//建立套接字
SOCKET s;
s=socket(AF_INET,SOCK_DGRAM,0);
if(s==INVALID_SOCKET)
{
cout<<"socket error"<<endl;
WSACleanup();
return 0;
}
//目的地址
sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(5000);
sin.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
//要发送的文件路径
char path[100]={"0"};
cout<<"请输入要发送文件的路径:(例如D:\\1.txt)"<<endl;
cin>>path;
//打开文件
FILE *fp;
fopen_s(&fp,path,"rb");
if(!fp)
{
cout<<"fopen_s error"<<endl;
return 0;
}
else
{
cout<<"文件已经打开,客户端等待传输"<<endl;
}
//发送缓存区
char sendbuf[1024]={0};
while (!feof(fp))
{
//清空sendbuf
memset(sendbuf,1,1024);
//把数据写入sendbuf
fread(sendbuf,1,1024,fp);
//发送sendbuf
int n=sendto(s,sendbuf,strlen(sendbuf),0,(sockaddr*)&sin,sizeof(sin));
if(n==SOCKET_ERROR)
{
cout<<"sendto error"<<endl;
closesocket(s);
WSACleanup();
return 0;
}
}
fclose(fp);
closesocket(s);
WSACleanup();
return 0;
}
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。