From 5cfef17cc20bb55f531649ea89b89a866c847810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kjist=C3=B3f?= Date: Sat, 3 Dec 2016 15:30:15 +0100 Subject: [PATCH] implemented cnm::close_connection() + general code cleaning + added TODOS --- chat_networking.hpp | 62 ++++++++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 23 deletions(-) diff --git a/chat_networking.hpp b/chat_networking.hpp index 4057a53..6135ae4 100644 --- a/chat_networking.hpp +++ b/chat_networking.hpp @@ -47,6 +47,18 @@ namespace chat }); } + void close_connection() + { + _ios.post([this] + { + _os << chat_message(message::BYE); + asio::write(_socket, _osb); + // TODO: handle last server message + _socket.close(); + _ios.stop(); + }); + } + /* internal methods */ private: @@ -71,53 +83,57 @@ namespace chat { throw_if_error(ec); - std::cout << receive_message_sync() << '\n'; - _os << chat_message(message::HELLO); _os << chat_message(message::NEPTUN, _login); std::reverse(_login.begin(), _login.end()); _os << chat_message(message::PASSW, _login); - asio::write(_socket, _osb); + asio::write(_socket, _osb); // handshake is handled synchronously + // TODO: do something with these couts (decide whether to display this or not) + std::cout << receive_message_sync() << '\n'; std::cout << receive_message_sync() << '\n'; std::cout << receive_message_sync() << '\n'; std::cout << receive_message_sync() << '\n'; - receive(); + receive(); // then flow goes to receive-loop } std::string receive_message_sync() { + boost::system::error_code ec; + std::string data; - asio::read_until(_socket, _isb, byte(message::TERM)); + asio::read_until(_socket, _isb, byte(message::TERM), ec); std::getline(_is, data, byte(message::TERM)); + throw_if_error(ec); return data; } void receive() { - asio::async_read_until(_socket, _isb, byte(message::TERM), - [this](boost::system::error_code ec, size_t) - { - throw_if_error(ec); + asio::async_read_until + (_socket, _isb, byte(message::TERM), + [this](boost::system::error_code ec, size_t) + { + throw_if_error(ec); - std::string data; - std::getline(_is, data, byte(message::TERM)); + std::string data; + std::getline(_is, data, byte(message::TERM)); - switch (data[0]) - { - // TODO: handle stuff - case byte(message::LOGIN): - std::cout << "login\n"; - break; - case byte(message::PING): - std::cout << "ping\n"; - break; - } + switch (data[0]) + { + // TODO: handle stuff + case byte(message::PING): + send(chat_message(message::PONG)); + break; + case byte(message::MESSAGE): + std::cout << data << '\n'; + break; + } - receive(); - }); + receive(); + }); } }; } \ No newline at end of file