From 33ece81cf15b3cb8d4a005194acc67c3a3e5ad35 Mon Sep 17 00:00:00 2001 From: crupest Date: Tue, 8 Jun 2021 20:50:30 +0800 Subject: import(life): ... --- works/life/computer-network-experiment/server.cpp | 26 ++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) (limited to 'works/life/computer-network-experiment/server.cpp') diff --git a/works/life/computer-network-experiment/server.cpp b/works/life/computer-network-experiment/server.cpp index 03d27ad..065687c 100644 --- a/works/life/computer-network-experiment/server.cpp +++ b/works/life/computer-network-experiment/server.cpp @@ -4,6 +4,7 @@ #include "Common.h" #include "IO.h" +#include "ReadWriteLock.h" #include #include @@ -26,12 +27,14 @@ const auto bind_address = "127.0.0.1"; // control bind address const u_short port = 1234; // control bind port +namespace { void PrintHelp() { SendOutput(CRUT( "Input and run one of following command:\n\t> NOTHING -> Continue and " "print new messages.\n\t> list -> List all connected client.\n\t> send " "[i] [message] -> Send messages to client with number i.\n")); } +} // namespace struct Connection { int id; @@ -45,9 +48,24 @@ struct Connection { folly::CancellationSource cancellation_source; }; +namespace { +cru::ReadWriteLock connections_lock; std::vector> connections; +void RemoveConnection(int id) { + connections_lock.WriteLock(); + connections.erase( + std::remove_if(connections.begin(), connections.end(), + [id](const std::unique_ptr &connection) { + return connection->id == id; + }), + connections.end()); + + connections_lock.WriteUnlock(); +} + void PrintConnections() { + connections_lock.ReadLock(); if (connections.empty()) { SendOutput(CRUT("Currently there is no connection.\n")); } @@ -58,7 +76,9 @@ void PrintConnections() { connection->address_string); } SendOutput(s); + connections_lock.ReadUnlock(); } +} // namespace void ResponseThreadProc(Connection *connection) { auto host = ConvertCharString(inet_ntoa(connection->address.sin_addr)); @@ -120,6 +140,8 @@ void ResponseThreadProc(Connection *connection) { } CloseSocket(connection->socket); + + RemoveConnection(connection->id); } void OnInputLine(StringView line) { @@ -164,7 +186,7 @@ void OnInputLine(StringView line) { [id](const std::unique_ptr &c) { return c->id == id; }); if (i == connections.end()) { - SendOutput(OutputType::Error, CRUT("No connection with such id.!\n")); + SendOutput(OutputType::Error, CRUT("No connection with such id.\n")); return; } @@ -224,6 +246,7 @@ int Main() { PrintErrorMessageAndExit(CRUT("Failed to accecpt.")); } + connections_lock.WriteLock(); connections.push_back(std::make_unique()); const std::unique_ptr &connection = connections.back(); @@ -233,5 +256,6 @@ int Main() { connection->thread = std::thread(ResponseThreadProc, connections.back().get()); connection->thread.detach(); + connections_lock.WriteUnlock(); } } -- cgit v1.2.3