51 lines
1.4 KiB
C++
51 lines
1.4 KiB
C++
/*
|
||
* connection.cpp
|
||
*
|
||
* Created on: 20 сент. 2022 г.
|
||
* Author: alexander
|
||
*/
|
||
|
||
#include <connection/connection.hpp>
|
||
#include <iostream>
|
||
|
||
namespace azh
|
||
{
|
||
Connection::Connection(boost::asio::io_context &ioContext) : _socket(ioContext)
|
||
{
|
||
}
|
||
|
||
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;
|
||
else
|
||
std::cout << "Sent " << bytesTransferred << " bytes" << std::endl;
|
||
});
|
||
|
||
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;
|
||
});
|
||
}
|
||
|
||
Connection::pointer Connection::create(boost::asio::io_context &ioContext)
|
||
{
|
||
return pointer(new Connection(ioContext));
|
||
}
|
||
}
|