From 03bce7d61a64fce9c54ae25e2e2a8543d82cc3bc Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Wed, 12 Mar 2025 21:23:17 +0800 Subject: feat!: require arg for server port --- src/main.cpp | 44 ++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 42 insertions(+), 2 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 115ad53..0ecd727 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,7 +1,9 @@ #include "chatServer.hpp" #include "log.hpp" +#include #include #include +#include static void handleSignal(int sig) { signal(sig, SIG_DFL); @@ -27,11 +29,49 @@ static void registerSignals() { signal(SIGPIPE, SIG_IGN); } +static void help() { + log(ERR, "usage: chat-server "); +} + // TODO: ARGC, ARGV. the CServer ctor should take a port number -int main() { +int main(int argc, char *argv[]) { + std::vector args{argv + 1, argv + argc}; + if (args.empty()) { + help(); + return 1; + } + uint16_t port = 0; + for (const auto &arg : args) { + if (arg == "-h" || arg == "--help") { + help(); + return 0; + } else if (std::ranges::all_of(arg, ::isdigit)) { + port = std::stoi(arg); + if (std::stoi(arg) < 0) { + log(ERR, "Port number must be greater than 0"); + + return 1; + } else if (std::stoi(arg) > 65535) { + log(ERR, "Port number must be less than 65536"); + + return 1; + } + + port = std::stoi(arg); + log(LOG, "Port number: {}", port); + } + } + + if (port == 0) { + log(ERR, "Port number is required"); + + help(); + return 1; + } + registerSignals(); - g_pChatServer = std::make_unique(); + g_pChatServer = std::make_unique(port); g_pChatServer->start(); // died -- cgit v1.2.3