Created
September 29, 2017 11:31
-
-
Save berkus/c23e114781eb55f131da2ba1a4ff57ff to your computer and use it in GitHub Desktop.
Coroutines TS plus Networking TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ctime> | |
#include <iostream> | |
#include <string> | |
#include <experimental/net> | |
using net = std::experimental::net; | |
using net::ip::tcp; | |
std::string make_daytime_string() { | |
using namespace std; // For time_t, time and ctime; | |
time_t now = time(0); | |
return ctime(&now); | |
} | |
void start_accept(net::io_context& io_service) { | |
tcp::acceptor acceptor{io_service, tcp::endpoint(tcp::v4(), 13)}; | |
while (1) { | |
tcp::socket socket(acceptor.get_io_service()); | |
auto error = co_await acceptor.async_accept(socket, net::co_future); | |
if (error) break; | |
std::string message = make_daytime_string(); | |
auto& [error, bytes] = co_await async_write( | |
socket, net::buffer(message), net::co_future | |
); | |
if (error) break; | |
} | |
} | |
int main() { | |
net::io_context io_service; | |
io_service.post([&io_service](){ | |
try { | |
start_accept(io_service); | |
} catch (const std::exception& e) { | |
std::cerr << e.what() << std::endl; | |
} | |
}); | |
io_service.run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment