C++ Socket編程 基礎四:類FTP 文件下載服務器 客戶端

服務器

#include <WINSOCK2.H>
#include <stdio.h>
#include <iostream>
#include <windows.h>
#include "package.h"
#pragma comment (lib,"ws2_32.lib")
using namespace ::std;
char * getByteFromFile(FILE * fp,char buf[],int start,int length){
	int sign;
	int c;
	int i=0;
	char set[6];
	c=getc(fp);
	while(!feof(fp)&&i<BUFFERLENGTH-1)
	{
		* (buf+i)=c;
		i++;
		c=getc(fp);
	}
	if (feof(fp))
	{
		set[0]='0';
		buf[i]='\0';
	} 
	else
	{
		set[0]='1';
		buf[i]=c;
	}
	buf[i+1]='\0';

	int f=1000;
	for (int j=1;j<5;j++)
	{
		set[j]=strlen(buf)/f%10+'0';
		f=f/10;
	}
	set[5]='\0';
	return set;
}

DWORD WINAPI serverFunction(LPVOID parameter){
	SOCKET acceptSock=(SOCKET)parameter;

	char receiveBuf[BUFFERLENGTH+1];//接收
	char sendBuf[BUFFERLENGTH+1];//接收

	strcpy(sendBuf,"hello!");
	printf("Send:%s\n",sendBuf); 
	send(acceptSock,sendBuf,strlen(sendBuf)+1,0);
	int len=recv(acceptSock,receiveBuf,sizeof(receiveBuf)-1,0);
	receiveBuf[len]='\0';
	printf("recv:%s\n",receiveBuf); 
	//將收到數據變爲文件名
	FILE * fp;
	if(strcmp(receiveBuf,"")==0) return -1;
	//查找文件是否存在
	if((fp=fopen(receiveBuf,"r"))==NULL)
	{
		printf("Can't open the %s",receiveBuf);
		send(acceptSock,"99999",6,0);
		return 0;
	}else{
		//傳輸文件
		char * head =(char* )malloc(sizeof(char)*(5+BUFFERLENGTH+1));
		do 
		{
			strcpy(head,getByteFromFile(fp,sendBuf,0,BUFFERLENGTH));
			strcat(head,sendBuf);
			//printf("%s",head);
			send(acceptSock,head,strlen(head)+1,0);
			Sleep(40);
		}while (head[0]=='1');
		fclose(fp);
		return 0;
	}
	
}
int main (){
	WSADATA WSAdata;
	SOCKET listenSock,acceptSock;
	SOCKADDR_IN addr_in;
	WORD versionRequest;
	versionRequest=MAKEWORD(2,2);
	int err;
	err=WSAStartup(versionRequest,&WSAdata);
	if(err){
		cout<<"Error: WSAStartup()!"<<endl;
	}
	if((listenSock=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_IP,NULL,0,WSA_FLAG_OVERLAPPED))==INVALID_SOCKET)
	{
		printf("error:  WSASocket()! error_number:%d",WSAGetLastError());
		return 1;
	}
	addr_in.sin_family=AF_INET;
	addr_in.sin_port=htons(SERVERPORT);
	addr_in.sin_addr.S_un.S_addr =htonl(INADDR_ANY);
	if(bind(listenSock, (sockaddr*)&addr_in, sizeof(sockaddr)) == SOCKET_ERROR)   
	{   
		printf(" Failed bind() \n");   
		return -1;   
	} 

	listen(listenSock,5);

	SOCKADDR_IN clientsocket;
	int len=sizeof(SOCKADDR);
	cout<<"server startup sucessful"<<endl;
	while(1) { 
		acceptSock=accept(listenSock,(SOCKADDR*)&clientsocket,&len);

		cout<<"new client in!"<<endl;
		CreateThread(NULL,0,serverFunction,(LPVOID)acceptSock,0,NULL);
	}
	WSACleanup();//釋放資源的操作
	return -1;
}
客戶端:

#include <WINSOCK2.H>
#include <stdio.h>
#include <iostream>
#include "package.h"
#pragma comment(lib,"ws2_32.lib")
using namespace ::std;

int getBytesLength(char* buf){
	char len[5];
	for(int i=1;i<5;i++){
		len[i-1]=buf[i];
	}
	len[4]='\0';
	return atoi(len);
}
int main(int argc,char **argv)
{
	int err;
	WORD versionRequired;
	WSADATA wsaData;
	versionRequired=MAKEWORD(1,1);
	char str[30];
	int segema=0;
		err=WSAStartup(versionRequired,&wsaData);//協議庫的版本信息
		printf("正在連接服務器!\n");
		char receiveBuf[BUFFERLENGTH+6];
		char sendBuf[BUFFERLENGTH+1];
	while (1)
	{


	SOCKET clientSocket=socket(AF_INET,SOCK_STREAM,0);

	SOCKADDR_IN clientsock_in;
	clientsock_in.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");
	clientsock_in.sin_family=AF_INET;
	clientsock_in.sin_port=htons(6000);
	connect(clientSocket,(SOCKADDR*)&clientsock_in,sizeof(SOCKADDR));//開始連接

	
	recv(clientSocket,receiveBuf,sizeof(receiveBuf),0);
	if (segema==0)
	{
		printf("服務器連接正常。接收:%s\n",receiveBuf); 
	}
	segema++;
	printf("請輸入文件名,輸入quit退出\n");
		cin>>str;
		if (strcmp(str,"quit")==0)
		{
			break;
		}
		int len=strlen(str)+1;
		send(clientSocket,str,len,0);
		FILE *outfp;
		if((outfp=fopen(str,"w"))==NULL)
		{
			printf("Can't save the %s\n",str);
			exit(2);
		}
		int bytesize=0;
		while (1)
		{
			int len=recv(clientSocket,receiveBuf,BUFFERLENGTH+5,0);
			receiveBuf[BUFFERLENGTH+5]='\0';
			if (len>0)
			{
				int flag=getBytesLength(receiveBuf);
				if (flag>0)
				{
					if (flag==strlen(receiveBuf)-5)
					{
						bytesize+=flag;
						printf("\b\b\b\b\b\b\b\b\b\\b\b\b\b\b\b\b\b\b\b\b已接收%d% Byte",bytesize);
						for(int i=5;i<strlen(receiveBuf);i++)
						{							
							putc(receiveBuf[i],outfp);
						}
					}
					if (receiveBuf[0]=='0'&&flag==strlen(receiveBuf)-5)
					{
						printf("\n\n文件%s下載完成\n\n\n",str);
						fclose(outfp);
						break;
					}
					if (receiveBuf[0]=='9')
					{
						 printf("文件%s不存在!\n",str);
						segema=1;
						break;
					}
				}
			}
		}
	
	closesocket(clientSocket);
	
	}
	WSACleanup();
	return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章