C++如何实现json形式的Socket传输图片
这篇文章给大家分享的是有关C++如何实现json形式的Socket传输图片的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
成都创新互联公司专业为企业提供浑江网站建设、浑江做网站、浑江网站设计、浑江网站制作等企业网站建设、网页设计与制作、浑江企业网站模板建站服务,10多年浑江做网站经验,不只是建网站,更提供有价值的思路和整体网络服务。
具体内容如下
大致流程:客户端读取图片,经过Base64编码,转成字符串的形式,保存到json中,通过socket传到服务端,然后Base64解码,再转换成图片
一.服务端
1.main.cpp
#include#include #include "Base64_1.h" #include #include "json1.hpp" #pragma comment(lib,"ws2_32.lib") using json = nlohmann::json; char revData[3888888]; bool WritePhotoFile(std::basic_string strFileName, std::string &strData) { HANDLE hFile; hFile = CreateFile(strFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { return false; } CBase64 base64; int datalen(0); DWORD dwritelen(0); std::string strdcode = base64.Decode(strData.data(), strData.size(), datalen); if (!WriteFile(hFile, strdcode.data(), datalen, &dwritelen, NULL)) { CloseHandle(hFile); return false; } CloseHandle(hFile); return true; } int main(int argc, char* argv[]) { //初始化WSA WORD sockVersion = MAKEWORD(2, 2); WSADATA wsaData; if (WSAStartup(sockVersion, &wsaData) != 0) { return 0; } //创建套接字 SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (slisten == INVALID_SOCKET) { printf("socket error !"); return 0; } //绑定IP和端口 sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(8888); sin.sin_addr.S_un.S_addr = INADDR_ANY; if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR) { printf("bind error !"); } //开始监听 if (listen(slisten, 5) == SOCKET_ERROR) { printf("listen error !"); return 0; } //循环接收数据 SOCKET sClient; sockaddr_in remoteAddr; int nAddrlen = sizeof(remoteAddr); //revData = (char*)malloc(sizeof(char) * 1000000); int i = 1; while (true) { printf("等待连接...\n"); sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen); if (sClient == INVALID_SOCKET) { printf("accept error !"); continue; } printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr)); //接收数据 int ret = recv(sClient, revData, 3888888, 0); if (ret > 0) { revData[ret] = 0x00; json o = json::parse(revData); for (json::iterator it = o.begin(); it != o.end(); ++it) { //std::cout << it.key() << " : " << it.value() << "\n"; if (it.key() == "imgA"|| it.key() == "imgB") { std::string num = std::to_string(i++); std::string strFileName = "D:\\"+ num +".jpg"; std::string val = it.value(); WritePhotoFile(strFileName, val); } } //std::cout<< json::parse(revData)<< std::endl; //printf(revData); } //发送数据 //const char * sendData = "你好,TCP客户端!\n"; //send(sClient, sendData, strlen(sendData), 0); closesocket(sClient); } closesocket(slisten); WSACleanup(); return 0; }
2.Base64.cpp
#include"Base64_1.h" CBase64::CBase64() { } CBase64::~CBase64() { } std::string CBase64::Encode(const char* Data, int DataByte) { //编码表 const char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //返回值 std::string strEncode; unsigned char Tmp[4] = { 0 }; int LineLength = 0; for (int i = 0; i<(int)(DataByte / 3); i++) { Tmp[1] = *Data++; Tmp[2] = *Data++; Tmp[3] = *Data++; strEncode += EncodeTable[Tmp[1] >> 2]; strEncode += EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F]; strEncode += EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F]; strEncode += EncodeTable[Tmp[3] & 0x3F]; if (LineLength += 4, LineLength == 76) { strEncode += "\r\n"; LineLength = 0; } } //对剩余数据进行编码 int Mod = DataByte % 3; if (Mod == 1) { Tmp[1] = *Data++; strEncode += EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode += EncodeTable[((Tmp[1] & 0x03) << 4)]; strEncode += "=="; } else if (Mod == 2) { Tmp[1] = *Data++; Tmp[2] = *Data++; strEncode += EncodeTable[(Tmp[1] & 0xFC) >> 2]; strEncode += EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)]; strEncode += EncodeTable[((Tmp[2] & 0x0F) << 2)]; strEncode += "="; } return strEncode; } std::string CBase64::Decode(const char* Data, int DataByte, int& OutByte) { //解码表 const char DecodeTable[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, // '+' 0, 0, 0, 63, // '/' 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9' 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z' 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z' }; //返回值 std::string strDecode; int nValue; int i = 0; while (i < DataByte) { if (*Data != '\r' && *Data != '\n') { nValue = DecodeTable[*Data++] << 18; nValue += DecodeTable[*Data++] << 12; strDecode += (nValue & 0x00FF0000) >> 16; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++] << 6; strDecode += (nValue & 0x0000FF00) >> 8; OutByte++; if (*Data != '=') { nValue += DecodeTable[*Data++]; strDecode += nValue & 0x000000FF; OutByte++; } } i += 4; } else// 回车换行,跳过 { Data++; i++; } } return strDecode; }
3.Base64_1.h
//++Base64.h #pragma once #includeclass CBase64 { public: public: CBase64(); ~CBase64(); /*编码 DataByte [in]输入的数据长度,以字节为单位 */ std::string Encode(const char* Data, int DataByte); /*解码 DataByte [in]输入的数据长度,以字节为单位 OutByte [out]输出的数据长度,以字节为单位,请不要通过返回值计算 输出数据的长度 */ std::string Decode(const char* Data, int DataByte, int& OutByte); };
4.json.hpp 去网上下载吧,个人感觉比jsoncpp好用一些(我里面的json1.hpp就是json.hpp)
二.客户端
1.main.cpp
#include#include #include #include #include #include #include "Bash74.h" #include "json1.hpp" using namespace std; using json = nlohmann::json; #pragma comment(lib, "ws2_32.lib") char chBuf1[3888888], chBuf2[3888888]; int main() { FILE *fIn1, *fIn2; int nRead1, nRead2; WORD sockVersion = MAKEWORD(2, 2); WSADATA data; if (WSAStartup(sockVersion, &data) != 0) { return 0; } std::string num = std::to_string(1); std::string chFileIn1 = "E:\\"+num+".jpg"; num = std::to_string(2); std::string chFileIn2 = "E:\\" + num + ".jpg"; SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sclient == INVALID_SOCKET) { printf("invalid socket!"); return 0; } sockaddr_in serAddr; serAddr.sin_family = AF_INET; serAddr.sin_port = htons(8888); serAddr.sin_addr.S_un.S_addr = inet_addr("192.168.3.72"); if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR) { //连接失败 printf("connect error !"); closesocket(sclient); return 0; } char chFileIn3[100], chFileIn4[100]; strcpy(chFileIn3, chFileIn1.c_str()); strcpy(chFileIn4, chFileIn2.c_str()); fIn1 = fopen(chFileIn3, "rb"); fIn2 = fopen(chFileIn4, "rb"); if (fIn1 == NULL || fIn2 == NULL) { printf("打开读取文件失败"); return 0; } //读文件 json data1; //fread()读取成功返回值为实际读回的数据个数(单位为Byte) nRead1 = fread(chBuf1, sizeof(char), 3888888, fIn1); nRead2 = fread(chBuf2, sizeof(char), 3888888, fIn2); //base64编码 封装进json string imgBase64_1 = base64_encode(chBuf1, nRead1); string imgBase64_2 = base64_encode(chBuf2, nRead2); data1["imgA"] = imgBase64_1; data1["imgB"] = imgBase64_2; fclose(fIn1); fclose(fIn2); //显式转换为string std::string s = data1.dump(); const char * sendData; sendData = s.c_str(); //string转const char* //char * sendData = "你好,TCP服务端,我是客户端\n"; send(sclient, sendData, strlen(sendData), 0); //send()用来将数据由指定的socket传给对方主机 //int send(int s, const void * msg, int len, unsigned int flags) //s为已建立好连接的socket,msg指向数据内容,len则为数据长度,参数flags一般设0 //成功则返回实际传送出去的字符数,失败返回-1,错误原因存于error char recData[266680]; int ret = recv(sclient, recData, 266680, 0); if (ret>0) { recData[ret] = 0x00; //printf(recData); } closesocket(sclient); WSACleanup(); system("pause"); return 0; }
2.Bash74.h
#ifndef __BASE64_H__ #define __BASE64_H__ #include#include static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(const char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(const char * bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i <4); i++) { ret += base64_chars[char_array_4[i]]; } i = 0; } } if (i) { for (j = i; j < 3; j++) { char_array_3[j] = '\0'; } char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) { ret += base64_chars[char_array_4[j]]; } while ((i++ < 3)) { ret += '='; } } return ret; } std::string base64_decode(std::string const & encoded_string) { int in_len = (int)encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j <4; j++) char_array_4[j] = 0; for (j = 0; j <4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } #endif
3.json.hpp 上面有链接(我里面的json1.hpp就是json.hpp)
Hit:服务端和客户端的Base64文件不一样,是因为当时服务端接收json时,Base64解码成图片出现了问题,又去找大神的博客,把服务端的Base64文件换了。然后能进行正常的传输图片,客户端就懒得换了~
感谢各位的阅读!关于“C++如何实现json形式的Socket传输图片”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
网站题目:C++如何实现json形式的Socket传输图片
链接地址:http://scyanting.com/article/gdsgsg.html