62 lines
1.4 KiB
C++
62 lines
1.4 KiB
C++
#include "Connection.h"
|
|
#include <functional>
|
|
#include <sstream>
|
|
|
|
|
|
namespace MailServer {
|
|
|
|
Connection::Connection(asio::io_service& ioService, const Util::Context& context) :
|
|
m_ioService(ioService),
|
|
m_socket(ioService),
|
|
m_protocol(context)
|
|
{
|
|
}
|
|
|
|
asio::ip::tcp::socket& Connection::Socket()
|
|
{
|
|
return m_socket;
|
|
}
|
|
|
|
void Connection::Start()
|
|
{
|
|
StartWrite(m_protocol.OpenConnection(m_socket.remote_endpoint().address().to_string()).second);
|
|
}
|
|
|
|
void Connection::StartRead()
|
|
{
|
|
m_socket.async_read_some(asio::buffer(m_data), std::bind(&Connection::HandleRead, this, std::placeholders::_1, std::placeholders::_2));
|
|
}
|
|
|
|
void Connection::HandleRead(const asio::error_code& ec, std::size_t length)
|
|
{
|
|
if (!ec)
|
|
{
|
|
Protocol::Protocol::Result result = m_protocol.ProcessMessage(std::string(m_data.begin(), m_data.begin() + length));
|
|
if (result.second.size() > 0)
|
|
StartWrite(result.second);
|
|
else
|
|
StartRead();
|
|
|
|
if (result.first == Protocol::Protocol::State::Disconnected)
|
|
m_socket.close();
|
|
}
|
|
}
|
|
|
|
void Connection::StartWrite(const std::string& message)
|
|
{
|
|
std::copy(message.begin(), message.end(), m_data.data());
|
|
|
|
size_t length = message.size() + 1;
|
|
m_data[message.size()] = '\n';
|
|
|
|
asio::async_write(m_socket, asio::buffer(m_data, length), std::bind(&Connection::HandleWrite, this, std::placeholders::_1));
|
|
}
|
|
|
|
void Connection::HandleWrite(const asio::error_code& ec)
|
|
{
|
|
if (!ec)
|
|
StartRead();
|
|
}
|
|
|
|
} // namespace MailServer
|