-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpserver.h
131 lines (104 loc) · 2.44 KB
/
tcpserver.h
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#ifndef TCPSERVER_H
#define TCPSERVER_H
#include <QObject>
#include <QTcpServer>
#include <QDataStream>
#include "d_format.hpp"
#include <QFile>
#include <QKeyEvent>
#include <QThread>
#include <boost/asio.hpp>
#include <thread>
class AsioTcpServer;
class TcpConnection: public std::enable_shared_from_this<TcpConnection>
{
public:
TcpConnection(boost::asio::ip::tcp::socket socket, AsioTcpServer *asioTcpServer)
: socket_(std::move(socket)), asioTcpServer(asioTcpServer)
{
}
~TcpConnection()
{
LOG("~TcpConnection");
}
void start()
{
doReadSize();
}
void doReadSize();
void doReadBody(uint32_t size);
void sendCmd(const std::string &cmd);
void processData();
boost::asio::ip::tcp::socket socket_;
uint32_t msgSize;
std::string data;
AsioTcpServer *asioTcpServer;
};
class AsioTcpServer : public QObject
{
Q_OBJECT
public:
AsioTcpServer(boost::asio::io_service& io_service,
const boost::asio::ip::tcp::endpoint& endpoint)
: acceptor_(io_service, endpoint),
socket_(io_service)
{
do_accept();
}
~AsioTcpServer()
{
LOG("~AsioTcpServer");
}
void processData(const std::string &data)
{
emit onNewData(data);
}
void processDisconnect()
{
connection.reset();
emit onDisconnect();
}
void sendCmd(const std::string &cmd)
{
std::lock_guard<std::mutex> lock(mutex);
if (connection)
{
connection->sendCmd(cmd);
}
}
private:
void do_accept();
boost::asio::ip::tcp::acceptor acceptor_;
boost::asio::ip::tcp::socket socket_;
std::mutex mutex;
std::shared_ptr<TcpConnection> connection;
signals:
void onNewConnection();
void onDisconnect();
void onNewData(const std::string &data);
};
class TcpServer : public QObject
{
Q_OBJECT
public:
explicit TcpServer(QObject *parent);
~TcpServer();
void start();
void stop();
signals:
void newObj(const Obj &obj);
void onNewConnection();
public slots:
void newConnection();
void disconnected();
void settingsChanged();
void sendKeyEvent(const Obj &obj);
void onNewData(const std::string &data);
private:
QFile outputFile;
//QThread thread;
boost::asio::io_service io_service;
std::thread thread;
std::unique_ptr<AsioTcpServer> asioTcpServer;
};
#endif // TCPSERVER_H