TCP 客户端发送文件到服务器

server.cpp

#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <WinSock2.h>
#include<string.h>

#pragma comment(lib,"wsock32.lib")

using namespace std;

//缓存大小设置不能超过2M
#define BUFF_SIZE (1024 * 256)
#define FILE_NAME_LENGTH 1024


int s;                     /* socket for accepting connections    */
int ns;                    /* socket connected to client          */


int getFileSize(char *filePath) {
    FILE *f;
    f = fopen(filePath, "rb");
    if (NULL == f) {
        printf("getFileSize fopen error\n");
        return -1;
    }

    if (0 != fseek(f, 0, SEEK_END)) {
        printf("getFileSize fseek error\n");
        return -1;
    }

    int fileSize = ftell(f);
    if (fileSize < 0) {
        printf("ftell error\n");
    }
    printf("fileSize:%lld\n", fileSize);
    fclose(f);
    return fileSize;
}

char *getFileName(char *filePath) {
    bool bFound = false;
    char *buff = new char[1024];
    memset(buff, 0, 1024);
    while (!bFound) {
        int lastIndex = 0;
        for (int i = 0; i < strlen(filePath); ++i) {
            if (filePath[i] == '\\' || filePath[i] == '/') {
                lastIndex = i;
            }
        }
        for (int i = lastIndex + 1; i < strlen(filePath); ++i) {
            buff[i - lastIndex - 1] = filePath[i];
        }
        bFound = true;
    }
    return buff;
}


int main(int argc, char **argv)
{
	// _onexit(exitFunc);
	unsigned short port;       /* port server binds to                */
	char buff[BUFF_SIZE];              /* buffer for sending & receiving data */
	struct sockaddr_in client; /* client address information          */
	struct sockaddr_in server; /* server address information          */
	int namelen;               /* length of client name               */
	char *filePath = new char[FILE_NAME_LENGTH];

	port = 23/*(unsigned short) atoi(argv[1])*/;

	//filePath = "C:\\Users\\18131\\Desktop\\期货窗口截图\\内存扫描.txt";


	int fileSize;
	char *fileName;

	WSADATA wsadata;
	WSAStartup(0x202, &wsadata);

	//创建socket服务
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("socket error\n");
		exit(2);
	}

	//socket和服务地址绑定
	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = inet_addr("127.0.0.1")/*INADDR_ANY*/;

	if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("bind error\n");
		exit(3);
	}

	//监听服务,只允许一个客户端连接
	if (listen(s, 1) != 0)
	{
		printf("listen error\n");
		exit(4);
	}

	//等待连接
	namelen = sizeof(client);
	//循环 一直等待客户端的连接
	if ((ns = accept(s, (struct sockaddr *)&client, &namelen)) == -1)
	{
		printf("accept error\n");
		//exit(5);
	}



	int fileRecv = 0;//记录接收文件
	FILE *f = NULL;//文件
	int totalFileSize = 0;

	while (true) {
		循环 一直等待客户端的连接

		int iRecv = 0;
		memset(buff, 0, BUFF_SIZE);
		iRecv = recv(ns, buff, BUFF_SIZE, 0);
		//解析接收到的消息
		char recvstr[BUFF_SIZE];
		strcpy(recvstr, buff);
		if (iRecv < 0) {
			printf("recv message error\n");
			//exit(5);
		}
		else
		{
			if (memcmp(buff, "filesize=", 9) == 0)//接收为文件大小
			{
			
				char tempbf[BUFF_SIZE];
				strcpy(tempbf, &buff[9]);
				totalFileSize = atoll(tempbf);
				printf("%s,%d\n", buff, totalFileSize);
				memset(buff, 0, BUFF_SIZE);
				//memset(tempbf, 0, BUFF_SIZE);
				//memset(buff, 0, BUFF_SIZE);

			}

			if (memcmp(buff, "fileName=", 9) == 0)//开始发送标志
			{
				printf("buff=%s\n", buff);
				char tempbf[BUFF_SIZE];
				strcpy(tempbf, &buff[9]);
				printf("tempbf=%s\n", tempbf);

				strcpy(filePath, "D:\\client\\");
				//filePath = ;
				//strcat()
				strcat(filePath, tempbf);

				printf("filePath=%s\n", filePath);


				创建接收文件

				f = fopen(filePath, "wb");
				if (f == NULL) {
					printf("file:%s doesn't exist and failed to create\n", filePath);
				}

				memset(tempbf, 0, BUFF_SIZE);
				memset(buff, 0, BUFF_SIZE);


				send(ns, "startsend", 9, 0);

				//printf("%s\n", recvstr);

			}

			if (memcmp(buff, "clientSend", 9) == 0)//开始发送标志
			{
				while (true)
				{

						int iRecv = 0;
						if (memcmp(buff, "clientSend", 9) != 0&&memcmp(buff, "SendFinish", 9) != 0)
						{
							memset(buff, 0, BUFF_SIZE);
							iRecv = recv(ns, buff, BUFF_SIZE, 0);
						}

						//解析接收到的消息
						char recvstr[BUFF_SIZE];
						strcpy(recvstr, buff);
						if (iRecv < 0) {
							printf("recv message error\n");
							//exit(5);
						}
						else
						{
							if (fileRecv <= totalFileSize&&buff[0]!='\0'&&memcmp(buff, "SendFinish", 9) != 0/*&&memcmp(buff, "clientSend", 9) != 0*/) {
								
								if (memcmp(buff, "clientSend", 9) != 0)
								{
									fileRecv += iRecv;
									fwrite(buff, 1, iRecv, f);
									printf("%s\n", buff);
								}
								//memset(tempbf1, 0, BUFF_SIZE);
								memset(buff, 0, BUFF_SIZE);

								send(ns, "recvEnd", 7, 0);
							}
							else
							{
								fclose(f);
								printf("传输完成?\n");
								break;
							}
						}
					}
				break;
			}
		}
	}
	system("pause");
}


client.cpp

#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS

#include <iostream>

#include <stdio.h>
#include <WinSock2.h>
#include <time.h>

#pragma comment(lib,"wsock32.lib")

using namespace std;

//缓存大小设置不能超过2M
#define BUFF_SIZE (1024 * 256)

#define FILE_NAME_LENGTH 1024

int s;                     /* client socket                       */

int getFileSize(char *filePath) {
	FILE *f;
	f = fopen(filePath, "rb");
	if (NULL == f) {
		printf("getFileSize fopen error\n");
		return -1;
	}

	if (0 != fseek(f, 0, SEEK_END)) {
		printf("getFileSize fseek error\n");
		return -1;
	}

	int fileSize = ftell(f);
	if (fileSize < 0) {
		printf("ftell error\n");
	}
	printf("fileSize:%lld\n", fileSize);
	fclose(f);
	return fileSize;
}

char *getFileName(char *filePath) {
	bool bFound = false;
	char *buff = new char[1024];
	memset(buff, 0, 1024);
	while (!bFound) {
		int lastIndex = 0;
		for (int i = 0; i < strlen(filePath); ++i) {
			if (filePath[i] == '\\' || filePath[i] == '/') {
				lastIndex = i;
			}
		}
		for (int i = lastIndex + 1; i < strlen(filePath); ++i) {
			buff[i - lastIndex - 1] = filePath[i];
		}
		bFound = true;
	}
	return buff;
}

/*
* Client Main.
*/
int main(int argc, char** argv)
{
	//_onexit(exitFunc);

	WSADATA wsadata;
	WSAStartup(0x202, &wsadata);
	printf("start...\n");

	unsigned short port;       //服务端口
	char buf[BUFF_SIZE];       //缓存
	struct hostent *hostnm;    //服务地址信息
	struct sockaddr_in server; //服务sockaddr信息

							   //传入两个参数,顺序是服务器地址和端口
	port = 23/* (unsigned short)atoi(argv[2])*/;

	server.sin_family = AF_INET;
	server.sin_port = htons(port);
	server.sin_addr.s_addr = inet_addr("127.0.0.1") /**((unsigned long *)hostnm->h_addr)*/;

	//创建socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		printf("Socket error\n");
	}

	//准备连接服务端
	printf("ready to connet to server ...\n");
	if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("Connect error\n");
	}

	char buff[BUFF_SIZE];              /* buffer for sending & receiving data */

	//获取要发送文件的信息
	char *filePath = new char[FILE_NAME_LENGTH];
	filePath = "C:\\Users\\18131\\Desktop\\期货窗口截图\\易联众PACS 3.6影像浏览工作站使用说明书.pdf";

	int fileSize = getFileSize(filePath);
	printf("fileSize:%lld\n", fileSize);
	char *fileName = getFileName(filePath);
	printf("fileName:%s\n", fileName);


	//打开文件
	FILE *f;
	f = fopen(filePath, "rb");
	if (f == NULL) {
		printf("file:%s doesn't exist\n", filePath);
		exit(6);
	}


	int sendSize = 0;
	//先将文件大小的数据发送给服务器
	_itoa(fileSize, buff, 10);
	char tempbuff[BUFF_SIZE];
	strcpy(tempbuff, buff);
	sprintf(buff, "filesize=%s", tempbuff);
	if (send(s, buff, sizeof(buff), 0) < 0) {
		printf("send fileSize to client error\n");
	}
	else
	{
		memset(buff, 0, BUFF_SIZE);
		printf("send fileSize to client sucess\n");
	}

	//再将文件名发送给服务器
	strcpy(tempbuff, fileName);
	sprintf(fileName, "fileName=%s", tempbuff);
	if (send(s, fileName, strlen(fileName), 0) < 0) {
		printf("send fileName to client error\n");
	}
	else
	{
		memset(fileName, 0, strlen(fileName));
		printf("send fileName to client sucess\n");
	}

	//发送文件真实开始

		while (true)
		{
			int iRecv = 0;
			memset(buff, 0, BUFF_SIZE);
			iRecv = recv(s, buff, BUFF_SIZE, 0);

			
				char recvEnd[BUFF_SIZE];
				memset(recvEnd, 0, BUFF_SIZE);

				if (memcmp(buff, "startsend", 9) == 0)
				{
					send(s, "clientSend", 10, 0);//开始发送

				    while (sendSize < fileSize) {

					if (memcmp(recvEnd, "recvEnd", 7) == 0)//判断是否接收完成
					{
						memset(buff, 0, BUFF_SIZE);
						size_t iread = fread(buff, 1, BUFF_SIZE, f);
						printf("iread:%d\n", iread);
						if (iread < 0) {
							printf("fread error\n");
							fclose(f);
							break;
						}

						int iSend = send(s, buff, iread, 0);
						if (iSend < 0) {
							printf("send error\n");
							fclose(f);
							break;
						}
						else
						{
							memset(buff, 0, BUFF_SIZE);
						}
						sendSize += iSend;
						printf("fileSize:%lld iSend:%d sendSize:%lld\n", fileSize, iSend, sendSize);
						fseek(f, sendSize, SEEK_SET);
						memset(recvEnd, 0, BUFF_SIZE);

					}
					recv(s, recvEnd, BUFF_SIZE, 0);//接收完成
			}
				send(s, "SendFinish", 10, 0);//告诉服务器文件发送完毕
				fclose(f);//关闭文件
				break;
		}
    }
	printf("Client Ended Successfully\n");
	//exit(0);
	system("pause");
}


上一篇:linux中的export与source


下一篇:servlet-response-download