-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtcpclient.cpp
80 lines (68 loc) · 2.15 KB
/
tcpclient.cpp
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
71
72
73
74
75
76
77
78
79
80
//
// Created by denis on 03.12.18.
//
#include <boost/asio.hpp>
#include <thread>
#include "format.hpp"
#include <iostream>
#include "tcpclient.hpp"
#include <boost/endian/conversion.hpp>
using boost::asio::ip::tcp;
void TcpClient::run() {
tcp::resolver resolver(io_service);
tcp::resolver::query query("localhost", "8400");
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
connect(socket, endpoint_iterator);
readTcpThread = std::thread([this](){
try
{
for (;;)
{
boost::system::error_code error;
uint32_t size;
read(socket, boost::asio::buffer(&size, sizeof(size)), error);
std::vector<char> data;
if (!error)
{
size = boost::endian::big_to_native(size);
data.resize(size);
read(socket, boost::asio::buffer(data.data(), size), error);
}
if (error == boost::asio::error::eof)
{
LOG("EOF");
break; // Connection closed cleanly by peer.
}
else if (error)
throw boost::system::system_error(error); // Some other error.
std::__cxx11::string command{data.data(), data.data() + data.size()};
std::istringstream iss(command);
Obj obj = readObj(iss);
if (iss)
inMsgs.push(obj);
else
LOG("ERROR parse obj");
}
}
catch (std::exception& e)
{
inMsgs.push(Obj());
std::cerr << e.what() << std::endl;
}
inMsgs.push(Obj());
LOG("TERMINATE TCP");
});
}
void TcpClient::sendCmd(std::__cxx11::string cmd)
{
uint32_t size = cmd.size();
size = boost::endian::native_to_big(size);
write(socket, boost::asio::buffer(&size, sizeof(size)));
write(socket, boost::asio::buffer(cmd, cmd.size()));
}
void TcpClient::sendObj(const Obj &obj)
{
std::ostringstream oss;
writeObj(oss, obj);
sendCmd(oss.str());
}