C++实现文件传输代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
/**********Receivefile client.cpp *************/
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSADATA wsaData;
int iResult=WSAStartup(MAKEWORD(2,2),&wsaData);
if (iResult!=NO_ERROR)
printf("Error at WSAStartup()\n");
SOCKET client;
client=socket(AF_INET,SOCKET_STREAM,IPPROTO_TCP);
if(client==INVALID_SOCKET){
printf("Error at socket():%ld\n",WSAGetLastError());
WSACleanup();
return;
}
sockaddr_in clientService;
clientService.sin_family=AF_INET;
clientService.sin_port=htons(8000);
clientService.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(client,(SOCKADDR*)&clientService,sizeof(clientService))==SOCKET_ERROR)
{
printf("Failed to connect.\n");
WSACleanup();
return;
}
char recvbuf[1024];
int read;
DWORD dwWrite;
BOOL bRet;
char filename[]="c:\\syn.txt";
HANDLE
hFile=CreateFile(filename,GENERIC_WRITE,0,0,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0);
while(true)
{
read=recv(client,recvbuf,1024,0);
if(read==-1) break;
bRet=WriteFile(hFile,recvbuf,read,&dwWrite,NULL);
if(bRet==FALSE)
{
MessageBox(NULL,"Write Buf ERROR!","ERROR",MB_OK);
break;
}
}
MessageBox(NULL,"Receive file OK!","OK",MB_OK);
return;
}
/****************** Sendfile server.cpp***********/
#include
#include
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSADATA wsaData;
int iResult=WSAStartup(MAKEWORD(2,2),&wsaData);
if(iResult!=NO_ERROR)
printf("ERROR at WSAStartup()\n");
SOCKET server;
server=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(server==INVALID_SOCKET)
{
printf("Error at socket():%ld\n",WSAGetLastError());
WSACleanup();
return;
}
sockaddr_in service;
service.sin_family=AF_INET;
service.sin_port=htons(8000);
service.sin_addr.s_addr=inet_addr("127.0.0.1");
if(bind(service,(SOCKADDR*)&service,sizeof(service))==SOCKET_ERROR)
{
printf("bind()failed.\n");
closesocket(service);
return;
}
if(listen(service,1)==SOCKET_ERROR)
printf("Error listening on socket.\n");
SOCKET AcceptSocket;
printf("Waiting for a client to connect...\n");
while(1)
{
AcceptSocket==SOCKET_ERROR;
while(AcceptSocket==SOCKET_ERROR)
{
AcceptSocket=accept(service,NULL,NULL);
}
printf("Client Connected.\n");
service=AcceptSocket;
break;
}
char sendbuf[1024];
DWORD dwRead;
BOOL bRet;
char filename[]="c:\\MyMain.java";
HANDLE
hFile=CreateFile(filename,GENERIC_READ,0,0,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
while(true)
{
bRet=ReadFile(hFile,sendbuf,1024,&dwRead,NULL);
if(bRet==FALSE)
{
MessageBox(NULL,"Read Bu
f ERROR!","Error",MB_OK);
break;
}
else if(dwRead==0)
{
MessageBox(NULL,"Send file OK!","OK",MB_OK);
break;
}
else
{
send(service,sendbuf,dwRead,0);
}
};
CloseHandle(hFile);
return;
}