|
| 1 | +#include <gflags/gflags.h> |
| 2 | +#include <iostream> |
| 3 | +#include <wangle/bootstrap/ClientBootstrap.h> |
| 4 | +#include <wangle/channel/AsyncSocketHandler.h> |
| 5 | +#include <wangle/channel/EventBaseHandler.h> |
| 6 | +#include <wangle/codec/LineBasedFrameDecoder.h> |
| 7 | +#include <wangle/codec/StringCodec.h> |
| 8 | + |
| 9 | +using namespace folly; |
| 10 | +using namespace wangle; |
| 11 | + |
| 12 | +DEFINE_int32(port, 8080, "echo server port"); |
| 13 | +DEFINE_string(host, "::1", "echo server address"); |
| 14 | + |
| 15 | +typedef Pipeline<folly::IOBufQueue&, std::string> EchoPipeline; |
| 16 | + |
| 17 | +// the handler for receiving messages back from the server |
| 18 | +class EchoHandler : public HandlerAdapter<std::string> { |
| 19 | + public: |
| 20 | + virtual void read(Context* ctx, std::string msg) override { |
| 21 | + std::cout << "received back: " << msg; |
| 22 | + } |
| 23 | + virtual void readException(Context* ctx, exception_wrapper e) override { |
| 24 | + std::cout << exceptionStr(e) << std::endl; |
| 25 | + close(ctx); |
| 26 | + } |
| 27 | + virtual void readEOF(Context* ctx) override { |
| 28 | + std::cout << "EOF received :(" << std::endl; |
| 29 | + close(ctx); |
| 30 | + } |
| 31 | +}; |
| 32 | + |
| 33 | +// chains the handlers together to define the response pipeline |
| 34 | +class EchoPipelineFactory : public PipelineFactory<EchoPipeline> { |
| 35 | + public: |
| 36 | + EchoPipeline::Ptr newPipeline(std::shared_ptr<AsyncTransportWrapper> sock) { |
| 37 | + auto pipeline = EchoPipeline::create(); |
| 38 | + pipeline->addBack(AsyncSocketHandler(sock)); |
| 39 | + pipeline->addBack( |
| 40 | + EventBaseHandler()); // ensure we can write from any thread |
| 41 | + pipeline->addBack(LineBasedFrameDecoder(8192, false)); |
| 42 | + pipeline->addBack(StringCodec()); |
| 43 | + pipeline->addBack(EchoHandler()); |
| 44 | + pipeline->finalize(); |
| 45 | + return pipeline; |
| 46 | + } |
| 47 | +}; |
| 48 | + |
| 49 | +int main(int argc, char** argv) { |
| 50 | + gflags::ParseCommandLineFlags(&argc, &argv, true); |
| 51 | + |
| 52 | + ClientBootstrap<EchoPipeline> client; |
| 53 | + client.group(std::make_shared<wangle::IOThreadPoolExecutor>(1)); |
| 54 | + client.pipelineFactory(std::make_shared<EchoPipelineFactory>()); |
| 55 | + auto pipeline = client.connect(SocketAddress(FLAGS_host, FLAGS_port)).get(); |
| 56 | + |
| 57 | + try { |
| 58 | + while (true) { |
| 59 | + std::string line; |
| 60 | + std::getline(std::cin, line); |
| 61 | + if (line == "") { |
| 62 | + break; |
| 63 | + } |
| 64 | + |
| 65 | + pipeline->write(line + "\r\n").get(); |
| 66 | + if (line == "bye") { |
| 67 | + pipeline->close(); |
| 68 | + break; |
| 69 | + } |
| 70 | + } |
| 71 | + } catch (const std::exception& e) { |
| 72 | + std::cout << exceptionStr(e) << std::endl; |
| 73 | + } |
| 74 | + |
| 75 | + return 0; |
| 76 | +} |
| 77 | + |
0 commit comments