C++实现客户端与服务器的通信(二):Base64编解码

关于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!"字符串了。

这次就写到这吧,接下来是图像传输与处理部分。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值