您好,登錄后才能下訂單哦!
本程序轉自騰訊課堂里面的《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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。