#include #include #include "server.hpp" using asio::ip::tcp; void Server::start(void) { ClientSocket* new_client = new ClientSocket(io_service_); acceptor_.async_accept(new_client->socket(), boost::bind(&Server::handle_accept, this, new_client, asio::placeholders::error)); } void Server::stop(void) { acceptor_.close(); } void Server::handle_accept(ClientSocket* new_client, const asio::error& error) { if (!error) { clients.push_back(new_client); asio::async_read_until(new_client->socket(), buffer, '\n', boost::bind(&Server::handle_read, this, new_client, asio::placeholders::error, asio::placeholders::bytes_transferred)); ClientSocket* new_client = new ClientSocket(io_service_); acceptor_.async_accept(new_client->socket(), boost::bind(&Server::handle_accept, this, new_client, asio::placeholders::error)); } else { delete new_client; } } void Server::promoteStringToClients(std::string str) { std::vector::iterator i; for (i=clients.begin(); i != clients.end(); ++i) { this.writeStringToSocket((*i)->socket(), str); } } void Server::writeStringToSocket(asio::ip::tcp::socket& sock, std::string str) { asio::async_write(sock, asio::buffer(str.c_str(), str.size()), boost::bind(&Server::handle_write, this, asio::placeholders::error, asio::placeholders::bytes_transferred)); } void Server::handle_write(const asio::error& error, std::size_t bytes_transferred) { if (!error) { std::vector::iterator i; for (i=clients.begin(); i != clients.end(); ++i) { asio::async_read_until((*i)->socket(), buffer, '\n', boost::bind(&Server::handle_read, this, *i, asio::placeholders::error, asio::placeholders::bytes_transferred)); } } } /* int main(int argc, char* argv[]) { try { asio::io_service io_service; Server s(io_service, 1338); s.start(); io_service.run(); } catch (asio::error& e) { std::cerr << e << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } */