geekbrains_network_programming/lesson_04/connection/connection.cpp

51 lines
1.4 KiB
C++
Raw Normal View History

2022-09-20 13:37:06 +00:00
/*
* connection.cpp
*
* Created on: 20 сент. 2022 г.
* Author: alexander
*/
#include <connection/connection.hpp>
#include <iostream>
namespace azh
{
2022-09-21 06:57:37 +00:00
Connection::Connection(io::ip::tcp::socket&& socket) : _socket(std::move(socket))
2022-09-20 13:37:06 +00:00
{
}
tcp::socket& Connection::socket()
{
return _socket;
}
void Connection::start()
{
auto strongThis = shared_from_this();
boost::asio::async_write(_socket, boost::asio::buffer(_message),
[strongThis](const boost::system::error_code &error, size_t bytesTransferred)
{
if (error)
std::cerr << "Failed to send message!" << std::endl;
2022-09-20 13:37:06 +00:00
else
std::cout << "Sent " << bytesTransferred << " bytes" << std::endl;
2022-09-20 13:37:06 +00:00
});
boost::asio::streambuf buffer;
_socket.async_receive(buffer.prepare(512), [this](const boost::system::error_code &error, size_t bytesTransferred)
{
if (error == boost::asio::error::eof)
std::cout << "Client disconnected properly!" << std::endl;
else if (error)
std::cerr << "Client disconnected in bad way!" << std::endl;
});
2022-09-20 13:37:06 +00:00
}
2022-09-21 06:57:37 +00:00
Connection::pointer Connection::create(io::ip::tcp::socket&& socket)
2022-09-20 13:37:06 +00:00
{
2022-09-21 06:57:37 +00:00
return pointer(new Connection(std::move(socket)));
2022-09-20 13:37:06 +00:00
}
}