您好,登錄后才能下訂單哦!
本程序轉(zhuǎn)自騰訊課堂里面的《C++之網(wǎng)絡(luò)編程》視頻教程里的。地址為 https://ke.qq.com/course/141506#term_id=100159728
服務(wù)器端:
#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;
}
//定義一個(gè)地址,并進(jìn)行綁定
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;
}
//接收緩存區(qū)
char recvbuf[MAX_BUF];
//初始化緩存區(qū)
memset(recvbuf,0,MAX_BUF);
//定義一個(gè)地址結(jié)構(gòu)
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<<"文件已經(jīng)打開,等待傳輸......"<<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;
}
客戶端:
本程序轉(zhuǎn)自騰訊課堂里面的《C++之網(wǎng)絡(luò)編程》視頻教程里的。地址為 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");
//要發(fā)送的文件路徑
char path[100]={"0"};
cout<<"請輸入要發(fā)送文件的路徑:(例如D:\\1.txt)"<<endl;
cin>>path;
//打開文件
FILE *fp;
fopen_s(&fp,path,"rb");
if(!fp)
{
cout<<"fopen_s error"<<endl;
return 0;
}
else
{
cout<<"文件已經(jīng)打開,客戶端等待傳輸"<<endl;
}
//發(fā)送緩存區(qū)
char sendbuf[1024]={0};
while (!feof(fp))
{
//清空sendbuf
memset(sendbuf,1,1024);
//把數(shù)據(jù)寫入sendbuf
fread(sendbuf,1,1024,fp);
//發(fā)送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;
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。