lichao
2021-05-25 5d8aa35858eea622e0e8e4a1f111fd408c483a31
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
70
/*
 * =====================================================================================
 *
 *       Filename:  tcp_server.cpp
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2021年05月19日 15时05分33秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Li Chao (), lichao@aiotlink.com
 *   Organization:  
 *
 * =====================================================================================
 */
 
#include "tcp_server.h"
#include "log.h"
#include "tcp_connection.h"
#include <chrono>
 
using namespace std::chrono_literals;
 
TcpServer::TcpServer(int port) :
    run_(false), listener_(io_, tcp::endpoint(tcp::v6(), port))
{
    Accept();
}
 
TcpServer::~TcpServer() { Stop(); }
 
bool TcpServer::Start()
{
    Stop();
    bool cur = false;
    if (run_.compare_exchange_strong(cur, true)) {
        auto proc = [this]() {
            while (run_) {
                io_.run_one_for(100ms);
            }
        };
        std::thread(proc).swap(worker_);
    }
}
void TcpServer::Stop()
{
    bool cur = true;
    if (run_.compare_exchange_strong(cur, false)) {
        io_.post([this]() {
            listener_.close();
        });
        std::this_thread::sleep_for(1s);
        if (worker_.joinable()) {
            worker_.join();
        }
    }
}
 
void TcpServer::Accept()
{
    listener_.async_accept([this](bserror_t ec, tcp::socket sock) {
        if (!ec) {
            LOG_INFO() << "server accept client";
            TcpReply1::Create(std::move(sock));
        }
        Accept();
    });
}