C++实现json形式的Socket传输图片

时间:2022-01-06 08:41:47

本文实例为大家分享了C++实现json形式的Socket传输图片的具体代码,供大家参考,具体内容如下

大致流程:客户端读取图片,经过Base64编码,转成字符串的形式,保存到json中,通过socket传到服务端,然后Base64解码,再转换成图片

一.服务端

C++实现json形式的Socket传输图片

1.main.cpp

  1. #include <iostream>
  2. #include <stdio.h>
  3. #include "Base64_1.h"
  4. #include <winsock2.h>
  5. #include "json1.hpp"
  6.  
  7. #pragma comment(lib,"ws2_32.lib")
  8. using json = nlohmann::json;
  9.  
  10. char revData[3888888];
  11.  
  12. bool WritePhotoFile(std::basic_string<TCHAR> strFileName, std::string &strData)
  13. {
  14. HANDLE hFile;
  15. hFile = CreateFile(strFileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  16.  
  17. if (hFile == INVALID_HANDLE_VALUE)
  18. {
  19. return false;
  20. }
  21.  
  22. CBase64 base64;
  23.  
  24. int datalen(0);
  25. DWORD dwritelen(0);
  26. std::string strdcode = base64.Decode(strData.data(), strData.size(), datalen);
  27. if (!WriteFile(hFile, strdcode.data(), datalen, &dwritelen, NULL))
  28. {
  29. CloseHandle(hFile);
  30. return false;
  31. }
  32. CloseHandle(hFile);
  33. return true;
  34. }
  35.  
  36. int main(int argc, char* argv[])
  37. {
  38. //初始化WSA
  39. WORD sockVersion = MAKEWORD(2, 2);
  40. WSADATA wsaData;
  41. if (WSAStartup(sockVersion, &wsaData) != 0)
  42. {
  43. return 0;
  44. }
  45.  
  46. //创建套接字
  47. SOCKET slisten = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  48. if (slisten == INVALID_SOCKET)
  49. {
  50. printf("socket error !");
  51. return 0;
  52. }
  53.  
  54. //绑定IP和端口
  55. sockaddr_in sin;
  56. sin.sin_family = AF_INET;
  57. sin.sin_port = htons(8888);
  58. sin.sin_addr.S_un.S_addr = INADDR_ANY;
  59.  
  60. if (bind(slisten, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
  61. {
  62. printf("bind error !");
  63. }
  64.  
  65. //开始监听
  66. if (listen(slisten, 5) == SOCKET_ERROR)
  67. {
  68. printf("listen error !");
  69. return 0;
  70. }
  71.  
  72. //循环接收数据
  73. SOCKET sClient;
  74. sockaddr_in remoteAddr;
  75. int nAddrlen = sizeof(remoteAddr);
  76.  
  77. //revData = (char*)malloc(sizeof(char) * 1000000);
  78. int i = 1;
  79. while (true)
  80. {
  81. printf("等待连接...\n");
  82. sClient = accept(slisten, (SOCKADDR *)&remoteAddr, &nAddrlen);
  83. if (sClient == INVALID_SOCKET)
  84. {
  85. printf("accept error !");
  86. continue;
  87. }
  88. printf("接受到一个连接:%s \r\n", inet_ntoa(remoteAddr.sin_addr));
  89.  
  90. //接收数据
  91. int ret = recv(sClient, revData, 3888888, 0);
  92. if (ret > 0)
  93. {
  94. revData[ret] = 0x00;
  95. json o = json::parse(revData);
  96. for (json::iterator it = o.begin(); it != o.end(); ++it) {
  97. //std::cout << it.key() << " : " << it.value() << "\n";
  98. if (it.key() == "imgA"|| it.key() == "imgB")
  99. {
  100. std::string num = std::to_string(i++);
  101. std::string strFileName = "D:\\"+ num +".jpg";
  102. std::string val = it.value();
  103. WritePhotoFile(strFileName, val);
  104. }
  105.  
  106. }
  107. //std::cout<< json::parse(revData)<< std::endl;
  108. //printf(revData);
  109. }
  110.  
  111. //发送数据
  112. //const char * sendData = "你好,TCP客户端!\n";
  113. //send(sClient, sendData, strlen(sendData), 0);
  114. closesocket(sClient);
  115. }
  116.  
  117. closesocket(slisten);
  118. WSACleanup();
  119.  
  120. return 0;
  121. }

2.Base64.cpp

  1. #include"Base64_1.h"
  2.  
  3. CBase64::CBase64()
  4. {
  5.  
  6. }
  7.  
  8. CBase64::~CBase64()
  9. {
  10.  
  11. }
  12.  
  13. std::string CBase64::Encode(const char* Data, int DataByte)
  14. {
  15. //编码表
  16. const char EncodeTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  17. //返回值
  18. std::string strEncode;
  19. unsigned char Tmp[4] = { 0 };
  20. int LineLength = 0;
  21. for (int i = 0; i<(int)(DataByte / 3); i++)
  22. {
  23. Tmp[1] = *Data++;
  24. Tmp[2] = *Data++;
  25. Tmp[3] = *Data++;
  26. strEncode += EncodeTable[Tmp[1] >> 2];
  27. strEncode += EncodeTable[((Tmp[1] << 4) | (Tmp[2] >> 4)) & 0x3F];
  28. strEncode += EncodeTable[((Tmp[2] << 2) | (Tmp[3] >> 6)) & 0x3F];
  29. strEncode += EncodeTable[Tmp[3] & 0x3F];
  30. if (LineLength += 4, LineLength == 76) { strEncode += "\r\n"; LineLength = 0; }
  31. }
  32. //对剩余数据进行编码
  33. int Mod = DataByte % 3;
  34. if (Mod == 1)
  35. {
  36. Tmp[1] = *Data++;
  37. strEncode += EncodeTable[(Tmp[1] & 0xFC) >> 2];
  38. strEncode += EncodeTable[((Tmp[1] & 0x03) << 4)];
  39. strEncode += "==";
  40. }
  41. else if (Mod == 2)
  42. {
  43. Tmp[1] = *Data++;
  44. Tmp[2] = *Data++;
  45. strEncode += EncodeTable[(Tmp[1] & 0xFC) >> 2];
  46. strEncode += EncodeTable[((Tmp[1] & 0x03) << 4) | ((Tmp[2] & 0xF0) >> 4)];
  47. strEncode += EncodeTable[((Tmp[2] & 0x0F) << 2)];
  48. strEncode += "=";
  49. }
  50.  
  51. return strEncode;
  52. }
  53.  
  54. std::string CBase64::Decode(const char* Data, int DataByte, int& OutByte)
  55. {
  56. //解码表
  57. const char DecodeTable[] =
  58. {
  59. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  60. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  61. 62, // '+'
  62. 0, 0, 0,
  63. 63, // '/'
  64. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // '0'-'9'
  65. 0, 0, 0, 0, 0, 0, 0,
  66. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
  67. 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // 'A'-'Z'
  68. 0, 0, 0, 0, 0, 0,
  69. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
  70. 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // 'a'-'z'
  71. };
  72. //返回值
  73. std::string strDecode;
  74. int nValue;
  75. int i = 0;
  76. while (i < DataByte)
  77. {
  78. if (*Data != '\r' && *Data != '\n')
  79. {
  80. nValue = DecodeTable[*Data++] << 18;
  81. nValue += DecodeTable[*Data++] << 12;
  82. strDecode += (nValue & 0x00FF0000) >> 16;
  83. OutByte++;
  84. if (*Data != '=')
  85. {
  86. nValue += DecodeTable[*Data++] << 6;
  87. strDecode += (nValue & 0x0000FF00) >> 8;
  88. OutByte++;
  89. if (*Data != '=')
  90. {
  91. nValue += DecodeTable[*Data++];
  92. strDecode += nValue & 0x000000FF;
  93. OutByte++;
  94. }
  95. }
  96. i += 4;
  97. }
  98. else// 回车换行,跳过
  99. {
  100. Data++;
  101. i++;
  102. }
  103. }
  104. return strDecode;
  105. }

3.Base64_1.h

  1. //++Base64.h
  2.  
  3. #pragma once
  4. #include <string>
  5.  
  6. class CBase64
  7. {
  8. public:
  9. public:
  10. CBase64();
  11. ~CBase64();
  12.  
  13. /*编码
  14. DataByte
  15. [in]输入的数据长度,以字节为单位
  16. */
  17. std::string Encode(const char* Data, int DataByte);
  18.  
  19. /*解码
  20. DataByte
  21. [in]输入的数据长度,以字节为单位
  22. OutByte
  23. [out]输出的数据长度,以字节为单位,请不要通过返回值计算
  24. 输出数据的长度
  25. */
  26. std::string Decode(const char* Data, int DataByte, int& OutByte);
  27.  
  28. };

4.json.hpp 去网上下载吧,个人感觉比jsoncpp好用一些(我里面的json1.hpp就是json.hpp

二.客户端

C++实现json形式的Socket传输图片

1.main.cpp

  1. #include<WINSOCK2.H>
  2. #include<STDIO.H>
  3. #include<iostream>
  4. #include<cstring>
  5. #include <string>
  6. #include <fstream>
  7. #include "Bash64.h"
  8. #include "json1.hpp"
  9.  
  10. using namespace std;
  11. using json = nlohmann::json;
  12. #pragma comment(lib, "ws2_32.lib")
  13.  
  14. char chBuf1[3888888], chBuf2[3888888];
  15.  
  16. int main()
  17. {
  18.  
  19. FILE *fIn1, *fIn2;
  20. int nRead1, nRead2;
  21.  
  22. WORD sockVersion = MAKEWORD(2, 2);
  23. WSADATA data;
  24. if (WSAStartup(sockVersion, &data) != 0)
  25. {
  26. return 0;
  27. }
  28.  
  29. std::string num = std::to_string(1);
  30. std::string chFileIn1 = "E:\\"+num+".jpg";
  31. num = std::to_string(2);
  32. std::string chFileIn2 = "E:\\" + num + ".jpg";
  33.  
  34. SOCKET sclient = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  35. if (sclient == INVALID_SOCKET)
  36. {
  37. printf("invalid socket!");
  38. return 0;
  39. }
  40.  
  41. sockaddr_in serAddr;
  42. serAddr.sin_family = AF_INET;
  43. serAddr.sin_port = htons(8888);
  44. serAddr.sin_addr.S_un.S_addr = inet_addr("192.168.3.72");
  45. if (connect(sclient, (sockaddr *)&serAddr, sizeof(serAddr)) == SOCKET_ERROR)
  46. { //连接失败
  47. printf("connect error !");
  48. closesocket(sclient);
  49. return 0;
  50. }
  51.  
  52. char chFileIn3[100], chFileIn4[100];
  53. strcpy(chFileIn3, chFileIn1.c_str());
  54. strcpy(chFileIn4, chFileIn2.c_str());
  55. fIn1 = fopen(chFileIn3, "rb");
  56. fIn2 = fopen(chFileIn4, "rb");
  57. if (fIn1 == NULL || fIn2 == NULL)
  58. {
  59. printf("打开读取文件失败");
  60. return 0;
  61. }
  62. //读文件
  63. json data1;
  64.  
  65. //fread()读取成功返回值为实际读回的数据个数(单位为Byte)
  66. nRead1 = fread(chBuf1, sizeof(char), 3888888, fIn1);
  67. nRead2 = fread(chBuf2, sizeof(char), 3888888, fIn2);
  68. //base64编码 封装进json
  69. string imgBase64_1 = base64_encode(chBuf1, nRead1);
  70. string imgBase64_2 = base64_encode(chBuf2, nRead2);
  71. data1["imgA"] = imgBase64_1;
  72. data1["imgB"] = imgBase64_2;
  73. fclose(fIn1);
  74. fclose(fIn2);
  75.  
  76. //显式转换为string
  77. std::string s = data1.dump();
  78. const char * sendData;
  79. sendData = s.c_str(); //string转const char*
  80. //char * sendData = "你好,TCP服务端,我是客户端\n";
  81. send(sclient, sendData, strlen(sendData), 0);
  82.  
  83. //send()用来将数据由指定的socket传给对方主机
  84. //int send(int s, const void * msg, int len, unsigned int flags)
  85. //s为已建立好连接的socket,msg指向数据内容,len则为数据长度,参数flags一般设0
  86. //成功则返回实际传送出去的字符数,失败返回-1,错误原因存于error
  87.  
  88. char recData[266680];
  89. int ret = recv(sclient, recData, 266680, 0);
  90. if (ret>0) {
  91. recData[ret] = 0x00;
  92. //printf(recData);
  93. }
  94. closesocket(sclient);
  95.  
  96. WSACleanup();
  97. system("pause");
  98. return 0;
  99.  
  100. }

2.Bash64.h

  1. #ifndef __BASE64_H__
  2. #define __BASE64_H__
  3.  
  4. #include <iostream>
  5. #include <string>
  6.  
  7. static const std::string base64_chars =
  8. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  9. "abcdefghijklmnopqrstuvwxyz"
  10. "0123456789+/";
  11.  
  12. static inline bool is_base64(const char c)
  13. {
  14. return (isalnum(c) || (c == '+') || (c == '/'));
  15. }
  16.  
  17. std::string base64_encode(const char * bytes_to_encode, unsigned int in_len)
  18. {
  19. std::string ret;
  20. int i = 0;
  21. int j = 0;
  22. unsigned char char_array_3[3];
  23. unsigned char char_array_4[4];
  24.  
  25. while (in_len--)
  26. {
  27. char_array_3[i++] = *(bytes_to_encode++);
  28. if (i == 3)
  29. {
  30. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  31. char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  32. char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  33. char_array_4[3] = char_array_3[2] & 0x3f;
  34. for (i = 0; (i <4); i++)
  35. {
  36. ret += base64_chars[char_array_4[i]];
  37. }
  38. i = 0;
  39. }
  40. }
  41. if (i)
  42. {
  43. for (j = i; j < 3; j++)
  44. {
  45. char_array_3[j] = '\0';
  46. }
  47.  
  48. char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
  49. char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
  50. char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
  51. char_array_4[3] = char_array_3[2] & 0x3f;
  52.  
  53. for (j = 0; (j < i + 1); j++)
  54. {
  55. ret += base64_chars[char_array_4[j]];
  56. }
  57.  
  58. while ((i++ < 3))
  59. {
  60. ret += '=';
  61. }
  62.  
  63. }
  64. return ret;
  65. }
  66.  
  67. std::string base64_decode(std::string const & encoded_string)
  68. {
  69. int in_len = (int)encoded_string.size();
  70. int i = 0;
  71. int j = 0;
  72. int in_ = 0;
  73. unsigned char char_array_4[4], char_array_3[3];
  74. std::string ret;
  75.  
  76. while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
  77. char_array_4[i++] = encoded_string[in_]; in_++;
  78. if (i == 4) {
  79. for (i = 0; i <4; i++)
  80. char_array_4[i] = base64_chars.find(char_array_4[i]);
  81.  
  82. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  83. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  84. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  85.  
  86. for (i = 0; (i < 3); i++)
  87. ret += char_array_3[i];
  88. i = 0;
  89. }
  90. }
  91. if (i) {
  92. for (j = i; j <4; j++)
  93. char_array_4[j] = 0;
  94.  
  95. for (j = 0; j <4; j++)
  96. char_array_4[j] = base64_chars.find(char_array_4[j]);
  97.  
  98. char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
  99. char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
  100. char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
  101.  
  102. for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
  103. }
  104.  
  105. return ret;
  106. }
  107. #endif

3.json.hpp  上面有链接(我里面的json1.hpp就是json.hpp)

Hit:服务端和客户端的Base64文件不一样,是因为当时服务端接收json时,Base64解码成图片出现了问题,又去找大神的博客,把服务端的Base64文件换了。然后能进行正常的传输图片,客户端就懒得换了~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://blog.csdn.net/weixin_42755375/article/details/81590967