C++實現客戶端與伺服器的通訊(二):Base64編解碼

wwww1244發表於2018-07-09

關於base64編碼,是網路上最常見的用於傳輸8Bit位元組碼的編碼方式之一,base64就是一種基於64個可列印字元來表示二進位制資料的方法,這裡就不再贅述了。

在HTTP環境中,常常需要將字串轉換為base64編碼,這部分程式可以封裝到兩個函式當中,原始碼如下:

一、base64.h和base64.cpp

  • base64_encode:將BYTE *型別的位元組流編碼為string型別的base64字串
  • base64_decode:將string型別的base64字串解碼為vector<BYTE>型別的位元組流

base64.h:

#ifndef _BASE64_H_
#define _BASE64_H_

#include <vector>
#include <string>

typedef unsigned char BYTE;

std::string       base64_encode(BYTE const* bindata, unsigned int binlength);
std::vector<BYTE> base64_decode(std::string const&);

#endif

base64.cpp:

#include <iostream>

#include "base64.h"

static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

static inline bool is_base64(BYTE c) {
  return (isalnum(c) || (c == '+') || (c == '/'));
}

std::string base64_encode(BYTE const* buf, unsigned int bufLen) {
  std::string ret;
  int i = 0;
  int j = 0;
  BYTE char_array_3[3];
  BYTE char_array_4[4];

  while (bufLen--) {
    char_array_3[i++] = *(buf++);
    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::vector<BYTE> base64_decode(std::string const& encoded_string) {
  int in_len = encoded_string.size();
  int i = 0;
  int j = 0;
  int in_ = 0;
  BYTE char_array_4[4], char_array_3[3];
  std::vector<BYTE> 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.push_back(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.push_back(char_array_3[j]);
  }

  return ret;
}


二、編寫測試程式

然後,我們希望在之前的伺服器通訊程式中使用base64編碼,只需要修改client和server的test.cpp檔案,新增相應的介面即可:

client test.cpp:

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <iostream>

#include "http.h"
#include "base64.h"

using namespace std;

int main(int argc, char *argv[])
{
  CurlHttp curl_http;
  string str_url = "http://192.168.1.125:8003";  // 地址、埠號
  string str_test = "Hello World!";
  string str_test_base64 = base64_encode((BYTE const*)str_test.c_str(), str_test.length());

  while (1) {
    cout << "Post data ...\n";
    
    string result;
    int res = curl_http.http_post(str_url.c_str(), str_test_base64.c_str(), &result);
    cout << "[Response]: " << result << '\n';
    
    sleep(1);
  }
  
  return 0;
}

server test.cpp:

// 只列出了env_handler函式,其餘部分不變

int env_handler(struct mg_connection *conn) 
{
  static int counter = 0;
  counter++;

  const char * encoded_data = conn->content;  // 服務端收到的訊息
  int encoded_len = conn->content_len;        // 服務端收到的訊息長度
  string str_encoded(encoded_data, encoded_len);
  printf("counter: %d, %s\n", counter, str_encoded.c_str());

  vector<BYTE> str_decoded_byte = base64_decode(str_encoded);
  int decoded_len = str_decoded_byte.size();
  string str_decoded;
  str_decoded.assign(str_decoded_byte.begin(), str_decoded_byte.end());
  mg_printf(conn, "Received: %s, %d", str_decoded.c_str(), counter);
  
  return 0;
}

編譯,執行兩個程式,應該能看到這樣的輸出:

客戶端:

Post data ...
[Response]: Received: Hello World!, 1
Post data ...
[Response]: Received: Hello World!, 2
Post data ...
[Response]: Received: Hello World!, 3
Post data ...
[Response]: Received: Hello World!, 4
Post data ...
[Response]: Received: Hello World!, 5
Post data ...
[Response]: Received: Hello World!, 6
Post data ...
[Response]: Received: Hello World!, 7
Post data ...
[Response]: Received: Hello World!, 8
Post data ...
[Response]: Received: Hello World!, 9
Post data ...
[Response]: Received: Hello World!, 10

客戶端的輸出和之前完全一致,字串經過編碼後又在伺服器端解碼傳送回來,因此在服務端看到的輸出如下:

counter: 1, SGVsbG8gV29ybGQh
counter: 2, SGVsbG8gV29ybGQh
counter: 3, SGVsbG8gV29ybGQh
counter: 4, SGVsbG8gV29ybGQh
counter: 5, SGVsbG8gV29ybGQh
counter: 6, SGVsbG8gV29ybGQh
counter: 7, SGVsbG8gV29ybGQh
counter: 8, SGVsbG8gV29ybGQh
counter: 9, SGVsbG8gV29ybGQh
counter: 10, SGVsbG8gV29ybGQh

可以看到編碼後的"Hello World!"字串了。

這次就寫到這吧,接下來是影象傳輸與處理部分。

相關文章