lichao
2021-05-27 026bbfaf2b5d73a26b8e2fa49158883ef64c211b
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/*
 * =====================================================================================
 *
 *       Filename:  tcp_proxy.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年05月19日 15时04分15秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), lichao@aiotlink.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include "tcp_proxy.h"
#include "defs.h"
#include "shm_socket.h"
#include "tcp_connection.h"
 
TcpProxy::TcpProxy() :
    run_(false) {}
 
TcpProxy::~TcpProxy() {}
 
bool TcpProxy::Start(bhome_shm::SharedMemory &shm)
{
    Stop();
    bool cur = false;
    if (!run_.compare_exchange_strong(cur, true)) { return false; }
 
    auto &mq = GetCenterInfo(shm)->mq_tcp_proxy_;
    local_.reset(new ShmSocket(mq.offset_, shm, mq.id_));
    auto localProc = [this](ShmSocket &sock, MsgI &msg, BHMsgHead &head) {
        auto &dest = head.dest();
        if (dest.ip().empty() || dest.port() == 0) { return; }
        Request(dest.ip(), dest.port(), msg.content());
    };
    local_->Start(1, localProc);
 
    auto proxyProc = [this]() {
        while (run_) {
            io_context_.run_one_for(std::chrono::milliseconds(100));
        }
    };
    std::thread(proxyProc).swap(worker_);
    return true;
}
 
void TcpProxy::Stop()
{
    bool cur = true;
    if (run_.compare_exchange_strong(cur, false)) {
        if (worker_.joinable()) {
            worker_.join();
        }
        local_.reset();
    }
}
 
bool TcpProxy::Request(const std::string &ip, int port, std::string &&content)
{
    if (content.empty()) { return false; }
 
    tcp::endpoint dest(ip::address::from_string(ip), port);
    TcpRequest1::Create(io_context_, dest, std::move(content), *local_);
}