From b000ae9e41b8699d1c7d6eefa0441ee05c970d25 Mon Sep 17 00:00:00 2001 From: littleblack111 Date: Thu, 13 Mar 2025 19:43:56 +0800 Subject: fix: NONEWLINE more explicit fixes a problem where all of socket wrote response is using NONE fmt(944b18bde52778b32c31dc23f3d90fc17b94794f) so all of them don't have \n --- src/format.hpp | 5 ++++- src/session.cpp | 18 ++++++++++++++++-- src/session.hpp | 2 ++ 3 files changed, 22 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/format.hpp b/src/format.hpp index 42a4458..dd210c0 100644 --- a/src/format.hpp +++ b/src/format.hpp @@ -9,6 +9,7 @@ enum eFormatType : int8_t { WARN, ERR, SYS, + NONEWLINE }; namespace NFormatter { @@ -34,8 +35,10 @@ inline std::string fmt(eFormatType type, std::string str) { prefix = ""; break; } - if (!str.empty() && str.back() != '\n' && !prefix.empty()) + + if (str.back() != '\n' && type != NONEWLINE) str += '\n'; + return prefix + str; } diff --git a/src/session.cpp b/src/session.cpp index 6744fc9..228f183 100644 --- a/src/session.cpp +++ b/src/session.cpp @@ -58,7 +58,7 @@ void CSession::onSend(const std::string &msg) { void CSession::recvLoop() { while (true) { - auto recvData = read(NFormatter::fmt(NONE, "{}: ", m_name)); + auto recvData = read(NFormatter::fmt(NONEWLINE, "{}: ", m_name)); if (!recvData->good) break; @@ -90,7 +90,7 @@ std::unique_ptr CSession::read() { } std::unique_ptr CSession::read(const std::string &msg) { - write("{}", msg, false); + write(NONEWLINE, "{}", msg, false); m_isReading = true; return read(); } @@ -159,6 +159,20 @@ bool CSession::write(std::format_string fmt, Args &&...args) { return true; } +template +bool CSession::write(eFormatType type, std::format_string fmt, Args &&...args) { + std::string msg = NFormatter::fmt(type, fmt, std::forward(args)...); + if (m_isReading) + msg.insert(0, "\n"); + + if (send(m_sockfd.get(), msg.c_str(), msg.size(), 0) < 0) { + onErrno(WRITE); + return false; + } + onSend(msg); + return true; +} + bool CSession::write(const std::string &msg) { return write("{}", msg); } diff --git a/src/session.hpp b/src/session.hpp index 65aa7a0..77687f9 100644 --- a/src/session.hpp +++ b/src/session.hpp @@ -25,6 +25,8 @@ class CSession { bool write(const std::string &msg); template bool write(std::format_string fmt, Args &&...args); + template + bool write(eFormatType type, std::format_string fmt, Args &&...args); void run(); -- cgit v1.2.3