您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關C++如何實現json形式的Socket傳輸圖片的內容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
具體內容如下
大致流程:客戶端讀取圖片,經過Base64編碼,轉成字符串的形式,保存到json中,通過socket傳到服務端,然后Base64解碼,再轉換成圖片
一.服務端
1.main.cpp
#include <iostream> #include <stdio.h> #include "Base64_1.h" #include <winsock2.h> #include "json1.hpp" #pragma comment(lib,"ws2_32.lib") using json = nlohmann::json; char revData[3888888]; bool WritePhotoFile(std::basic_string<TCHAR> 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 #include <string> class 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<WINSOCK2.H> #include<STDIO.H> #include<iostream> #include<cstring> #include <string> #include <fstream> #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 <iostream> #include <string> 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傳輸圖片”這篇文章就分享到這里了,希望以上內容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。