IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> TCP 客户端发送文件到服务器 -> 正文阅读

[网络协议]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");
}


  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-08-05 17:42:25  更:2021-08-05 17:44:18 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年12日历 -2024/12/27 13:32:30-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码
数据统计