cpp11chat/server.cpp

69 lines
1.7 KiB
C++

#include <iostream>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/read.hpp>
#include <ctime>
using namespace boost::asio;
using namespace boost::asio::ip;
io_service ioservice;
tcp::endpoint tcpendpoint{tcp::v4(), 2222};
tcp::acceptor tcpacceptor{ioservice, tcpendpoint};
tcp::socket sock{ioservice};
std::vector<char> alldata;
std::array<char, 4096> data;
void read_handler(const boost::system::error_code& ec, std::size_t transferred)
{
if (!ec)
{
std::cout.write(data.data(), transferred);
for (int i = 0; i < transferred; ++i)
alldata.push_back(data[i]);
sock.async_read_some(buffer(data), read_handler);
}
}
void write_handler(const boost::system::error_code& ec, std::size_t transferred)
{
if (!ec)
{
tcp::endpoint remoteendpoint = sock.remote_endpoint();
address ip = remoteendpoint.address();
std::cout << transferred
<< " bytes transferred to "
<< ip.to_string() << ":" << remoteendpoint.port()
<< std::endl;
sock.async_read_some(buffer(data), read_handler);
}
}
void accept_handler(const boost::system::error_code& ec)
{
if (!ec)
{
std::time_t now = std::time(nullptr);
std::string time(std::ctime(&now));
async_write(sock, buffer(time), write_handler);
}
}
int main()
{
tcpacceptor.listen();
tcpacceptor.async_accept(sock, accept_handler);
// work, so the server does not stop listening
auto work = std::make_shared<io_service::work>(ioservice);
ioservice.run();
return EXIT_SUCCESS;
}