Skip to content

Instantly share code, notes, and snippets.

@promi
Last active January 7, 2017 17:06
Show Gist options
  • Save promi/659fd1cf585238863667c0ed3709d565 to your computer and use it in GitHub Desktop.
Save promi/659fd1cf585238863667c0ed3709d565 to your computer and use it in GitHub Desktop.
#include <string>
#include <stdexcept>
#include <memory>
#include <iostream>
#include <uvw.hpp>
int
main(void)
{
auto loop = uvw::Loop::getDefault ();
if (loop == nullptr)
{
throw std::runtime_error ("loop init failed");
}
auto tcp = loop->resource<uvw::TcpHandle>();
if (tcp == nullptr)
{
throw std::runtime_error ("tcp init failed");
}
tcp->once<uvw::ConnectEvent> ([] (const uvw::ConnectEvent &, uvw::TcpHandle &tcp) mutable
{
tcp.read ();
});
tcp->once<uvw::ErrorEvent> ([] (const uvw::ErrorEvent &, uvw::TcpHandle &) mutable
{
std::cerr << "Connection error\n";
});
std::string buf;
tcp->on<uvw::DataEvent> ([&] (const uvw::DataEvent &event, uvw::TcpHandle &tcp) mutable
{
std::string data {event.data.get (), event.length};
buf += data;
std::string::size_type pos;
while ((pos = buf.find ('\n')) != std::string::npos)
{
std::string line = buf.substr (0, pos);
buf.erase (0, pos + 1);
if (!line.compare (0, 2, "OK"))
{
const std::string idle = "idle\n";
std::unique_ptr<char[]> ptr {new char[idle.size ()]};
idle.copy (ptr.get (), idle.size ());
tcp.write (std::move (ptr), idle.size ());
}
else
{
std::cout << line << "\n";
}
}
});
tcp->connect ("127.0.0.1", 7701);
loop->run<uvw::Loop::Mode::DEFAULT> ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment