connection.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <boost/asio/write.hpp>
  2. #include <boost/bind.hpp>
  3. #include "connection.h"
  4. connection::connection(boost::asio::io_service& ioService, const context& context) :
  5. m_ioService(ioService),
  6. m_socket(ioService),
  7. m_protocol(context)
  8. {
  9. }
  10. boost::asio::ip::tcp::socket& connection::socket()
  11. {
  12. return m_socket;
  13. }
  14. void connection::start()
  15. {
  16. start_write(m_protocol.openConnection(m_socket.remote_endpoint().address().to_string()).second);
  17. }
  18. void connection::start_read()
  19. {
  20. m_socket.async_read_some(boost::asio::buffer(m_data), boost::bind(&connection::handle_read, this, _1, _2));
  21. }
  22. void connection::handle_read(const boost::system::error_code& ec, std::size_t length)
  23. {
  24. if (!ec)
  25. {
  26. protocol::result result = m_protocol.processMessage(std::string(m_data.begin(), m_data.begin() + length));
  27. if (result.second.size() > 0)
  28. start_write(result.second);
  29. else
  30. start_read();
  31. if (result.first == protocol::state::disconnected)
  32. m_socket.close();
  33. }
  34. }
  35. void connection::start_write(const std::string& message)
  36. {
  37. std::copy(message.begin(), message.end(), m_data.data());
  38. size_t length = message.size() + 1;
  39. m_data[message.size()] = '\n';
  40. boost::asio::async_write(m_socket, boost::asio::buffer(m_data, length), boost::bind(&connection::handle_write, this, _1));
  41. }
  42. void connection::handle_write(const boost::system::error_code& ec)
  43. {
  44. if (!ec)
  45. start_read();
  46. }