這篇文章給大家分享的是有關(guān)C++如何實(shí)現(xiàn)json形式的Socket傳輸圖片的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
成都創(chuàng)新互聯(lián)公司專業(yè)為企業(yè)提供渾江網(wǎng)站建設(shè)、渾江做網(wǎng)站、渾江網(wǎng)站設(shè)計(jì)、渾江網(wǎng)站制作等企業(yè)網(wǎng)站建設(shè)、網(wǎng)頁(yè)設(shè)計(jì)與制作、渾江企業(yè)網(wǎng)站模板建站服務(wù),10多年渾江做網(wǎng)站經(jīng)驗(yàn),不只是建網(wǎng)站,更提供有價(jià)值的思路和整體網(wǎng)絡(luò)服務(wù)。
具體內(nèi)容如下
大致流程:客戶端讀取圖片,經(jīng)過(guò)Base64編碼,轉(zhuǎn)成字符串的形式,保存到j(luò)son中,通過(guò)socket傳到服務(wù)端,然后Base64解碼,再轉(zhuǎn)換成圖片
一.服務(wù)端

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;
}
//創(chuàng)建套接字
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 !");
}
//開(kāi)始監(jiān)聽(tīng)
if (listen(slisten, 5) == SOCKET_ERROR)
{
printf("listen error !");
return 0;
}
//循環(huán)接收數(shù)據(jù)
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("接受到一個(gè)連接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
//接收數(shù)據(jù)
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);
}
//發(fā)送數(shù)據(jù)
//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; }
}
//對(duì)剩余數(shù)據(jù)進(jìn)行編碼
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// 回車換行,跳過(guò)
{
Data++;
i++;
}
}
return strDecode;
}3.Base64_1.h
//++Base64.h
#pragma once
#include <string>
class CBase64
{
public:
public:
CBase64();
~CBase64();
/*編碼
DataByte
[in]輸入的數(shù)據(jù)長(zhǎng)度,以字節(jié)為單位
*/
std::string Encode(const char* Data, int DataByte);
/*解碼
DataByte
[in]輸入的數(shù)據(jù)長(zhǎng)度,以字節(jié)為單位
OutByte
[out]輸出的數(shù)據(jù)長(zhǎng)度,以字節(jié)為單位,請(qǐng)不要通過(guò)返回值計(jì)算
輸出數(shù)據(jù)的長(zhǎng)度
*/
std::string Decode(const char* Data, int DataByte, int& OutByte);
};4.json.hpp 去網(wǎng)上下載吧,個(gè)人感覺(jué)比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("打開(kāi)讀取文件失敗");
return 0;
}
//讀文件
json data1;
//fread()讀取成功返回值為實(shí)際讀回的數(shù)據(jù)個(gè)數(shù)(單位為Byte)
nRead1 = fread(chBuf1, sizeof(char), 3888888, fIn1);
nRead2 = fread(chBuf2, sizeof(char), 3888888, fIn2);
//base64編碼 封裝進(jìn)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);
//顯式轉(zhuǎn)換為string
std::string s = data1.dump();
const char * sendData;
sendData = s.c_str(); //string轉(zhuǎn)const char*
//char * sendData = "你好,TCP服務(wù)端,我是客戶端\n";
send(sclient, sendData, strlen(sendData), 0);
//send()用來(lái)將數(shù)據(jù)由指定的socket傳給對(duì)方主機(jī)
//int send(int s, const void * msg, int len, unsigned int flags)
//s為已建立好連接的socket,msg指向數(shù)據(jù)內(nèi)容,len則為數(shù)據(jù)長(zhǎng)度,參數(shù)flags一般設(shè)0
//成功則返回實(shí)際傳送出去的字符數(shù),失敗返回-1,錯(cuò)誤原因存于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;
}
#endif3.json.hpp 上面有鏈接(我里面的json1.hpp就是json.hpp)
Hit:服務(wù)端和客戶端的Base64文件不一樣,是因?yàn)楫?dāng)時(shí)服務(wù)端接收json時(shí),Base64解碼成圖片出現(xiàn)了問(wèn)題,又去找大神的博客,把服務(wù)端的Base64文件換了。然后能進(jìn)行正常的傳輸圖片,客戶端就懶得換了~
感謝各位的閱讀!關(guān)于“C++如何實(shí)現(xiàn)json形式的Socket傳輸圖片”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
分享題目:C++如何實(shí)現(xiàn)json形式的Socket傳輸圖片
地址分享:http://chinadenli.net/article36/gdsgsg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App設(shè)計(jì)、定制開(kāi)發(fā)、微信小程序、動(dòng)態(tài)網(wǎng)站、網(wǎng)站制作、域名注冊(cè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)