From 68cac85ea58c69301645167f92d94bdb6e360753 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 8 Jun 2021 10:16:22 +0800 Subject: import(life): ... --- works/life/computer-network-experiment/client.cpp | 59 ++++++++++++++++++++--- 1 file changed, 52 insertions(+), 7 deletions(-) (limited to 'works/life/computer-network-experiment/client.cpp') diff --git a/works/life/computer-network-experiment/client.cpp b/works/life/computer-network-experiment/client.cpp index a8ce8cf..c206856 100644 --- a/works/life/computer-network-experiment/client.cpp +++ b/works/life/computer-network-experiment/client.cpp @@ -5,6 +5,9 @@ #include "Common.h" #include "IO.h" +#include +#include + #ifdef WIN32 #include #include @@ -12,12 +15,29 @@ #include #include #include - #endif const auto connect_address = "127.0.0.1"; // control connect address const u_short port = 1234; // control connect port +namespace { +folly::ProducerConsumerQueue send_queue(100); +folly::CancellationSource cancellation_source; +} // namespace + +void PrintHelp() { + SendOutput(CRUT("Input anything to send to server. Or just enter to receive " + "lastest messages from server.\n")); +} + +void OnInputLine(StringView line) { + if (line.empty()) { + return; + } else { + send_queue.write(ConvertCharStringBack(line) + '\n'); + } +} + int Main() { int client_socket; @@ -37,17 +57,42 @@ int Main() { PrintErrorMessageAndExit(CRUT("Failed to connect!")); } - String name; - { - auto guard = BlockOutputThread(); - output_stream << CRUT("Please input your name:"); - name = ReadInputLine(); - } + output_stream << CRUT("Please input your name:\n> "); + String name = ReadInputLine(); + + PrintHelp(); + + StartIOThread(); name.push_back(CRUT('\n')); auto name_data = ConvertCharStringBack(name); SafeSend(client_socket, name_data); + std::thread receive_thread([client_socket] { + std::string rest; + while (true) { + if (cancellation_source.isCancellationRequested()) { + break; + } + + std::string s = SafeReadUntil(client_socket, '\n', rest); + + SendOutput(CRUT("Recived a message:\n{}\n"), ConvertCharString(s)); + } + }); + receive_thread.detach(); + + while (true) { + if (cancellation_source.isCancellationRequested()) { + break; + } + + std::string s; + if (send_queue.read(s)) { + SafeSend(client_socket, s); + } + } + CloseSocket(client_socket); return 0; } -- cgit v1.2.3