Socket 发送接收图像

客户端代码:


#include 
#include 
#include 
#pragma comment(lib,"ws2_32.lib")
using namespace std;

size_t getSize()
{
	FILE * file;
	file = fopen("1.jpg", "rb");
	size_t sizeOfPic;

	fseek(file, 0, SEEK_END);   ///将文件指针移动文件结尾
	sizeOfPic = ftell(file); ///求出当前文件指针距离文件开始的字节数
	fclose(file);
	
	return sizeOfPic;
}

void main()
{
	WSADATA wsaData;
	SOCKET sockClient;//客户端Socket
	SOCKADDR_IN addrServer;//服务端地址
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	//新建客户端socket
	sockClient = socket(AF_INET, SOCK_STREAM, 0);
	//定义要连接的服务端地址
	addrServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//目标IP(127.0.0.1是回送地址)
	addrServer.sin_family = AF_INET;
	addrServer.sin_port = htons(6000);//连接端口6000
	//连接到服务端
	connect(sockClient, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));
	//发送数据
//	char message[20] = "HelloSocket!";
	char recvBuf[30];
	char size[20];
	size_t pic_size = getSize();
	itoa(pic_size, size, 10);
	send(sockClient, size, strlen(size) + 1, 0);
	recv(sockClient, recvBuf, 1024, 0);
	if (strcmp(recvBuf, "success!") == 0)
	{
		printf("%s\n", recvBuf);

		FILE * file;
		file = fopen("1.jpg", "rb");
		char buf[1024];
		while (!feof(file))
		{
			memset(buf, 0, sizeof(buf));
			size_t readlen = fread(buf, sizeof(char), sizeof(buf), file);
			send(sockClient, buf, readlen, 0);
		}
		fclose(file);
	}
	
	//关闭socket
	closesocket(sockClient);
	WSACleanup();
}

服务端代码:

#include 
#include 
#pragma comment(lib,"ws2_32.lib")
void main()
{
	WSADATA wsaData;
	SOCKET sockServer;
	SOCKADDR_IN addrServer;
	SOCKET sockClient;
	SOCKADDR_IN addrClient;
	WSAStartup(MAKEWORD(2, 2), &wsaData);
	sockServer = socket(AF_INET, SOCK_STREAM, 0);
	addrServer.sin_addr.S_un.S_addr = htonl(INADDR_ANY);//INADDR_ANY表示任何IP
	addrServer.sin_family = AF_INET;
	addrServer.sin_port = htons(6000);//绑定端口6000
	bind(sockServer, (SOCKADDR*)&addrServer, sizeof(SOCKADDR));

	//Listen监听端
	listen(sockServer, 5);//5为等待连接数目
	printf("服务器已启动:\n监听中...\n");
	int len = sizeof(SOCKADDR);
	char sendBuf[1024];//发送至客户端的字符串
	char recvBuf[1024];//接受客户端返回的字符串
	char flag[30] = "success!";

	//会阻塞进程,直到有客户端连接上来为止
	sockClient = accept(sockServer, (SOCKADDR*)&addrClient, &len);
	//接收并打印客户端数据
	recv(sockClient, recvBuf, 1024, 0);
	int size = atoi(recvBuf);
	if (size > 0)
	{
		send(sockClient, flag, strlen(flag) + 1, 0);
		printf("%s\n", recvBuf);

		FILE * file;
		file = fopen("1.jpg", "wb");
		while (size > 0)
		{
			int recvLen = recv(sockClient, recvBuf, 1024, 0);
			size_t writelen = fwrite(recvBuf, sizeof(char), recvLen, file);
			size -= recvLen;
		}
		fclose(file);
		
	}
	

	//关闭socket
	closesocket(sockClient);
	WSACleanup();
}


你可能感兴趣的:(C++编程)