-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.cpp
More file actions
59 lines (49 loc) · 1.37 KB
/
Connection.cpp
File metadata and controls
59 lines (49 loc) · 1.37 KB
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
#include "Connection.h"
#include "Messages.h"
#include <iostream>
#include <boost/bind.hpp>
Connection::Connection(boost::asio::io_context& ioContext) :
socket(ioContext)
{
}
Connection::handler Connection::createConnection(boost::asio::io_context& ioContext)
{
return std::make_shared<Connection>(ioContext);
}
tcp::socket& Connection::getSocket()
{
return socket;
}
void Connection::sendMessage(std::string_view message)
{
boost::asio::async_write(socket, boost::asio::buffer(message),
boost::bind(&Connection::handleWrite, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void Connection::startReading()
{
boost::asio::async_read_until(socket, buffer, "\r\n",
boost::bind(&Connection::handleRead, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void Connection::startConnection()
{
sendMessage(Messages::welcomeMessage);
startReading();
}
void Connection::handleWrite(const boost::system::error_code&, size_t)
{
}
void Connection::handleRead(const boost::system::error_code& error, size_t bytes)
{
if (!error)
{
std::istream is(&buffer);
std::string line;
std::getline(is, line);
message = line;
}
startReading();
}