Able to send and receive messages, server panicking and not relaying userids yet

This commit is contained in:
2026-02-09 20:35:17 +01:00
parent a0d9d9c6de
commit 38f6488ba1
12 changed files with 171 additions and 13 deletions

View File

@@ -1,6 +1,9 @@
cmake_minimum_required(VERSION 3.23)
project(chat_server LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
file(GLOB_RECURSE SOURCES "src/*.ui" "src/*.cpp" "inc/*.h" "res/*.qrc")
add_executable(chat_server

View File

@@ -5,6 +5,7 @@
#include "services.grpc.pb.h"
#include <grpcpp/server_context.h>
#include <grpcpp/support/server_callback.h>
#include <map>
class Service : public chat::Chat::CallbackService {
public:
@@ -14,7 +15,7 @@ public:
void sendToAll(const chat::chatMsg &msg);
private:
std::vector<ChatReactor *> m_clients;
std::map<std::string, ChatReactor *> m_clients;
absl::Mutex m_mu;
std::vector<chat::chatMsg> m_messages ABSL_GUARDED_BY(m_mu);
};

View File

@@ -9,6 +9,7 @@ ChatReactor::ChatReactor(Service *service, absl::Mutex *mu,
void ChatReactor::OnReadDone(bool ok) {
if (ok) {
std::cout << "Received message: " << m_msg.message() << std::endl;
m_mu->lock();
m_messages->push_back(m_msg);
m_mu->unlock();

View File

@@ -1,21 +1,29 @@
#include "logic/service.h"
#include "logic/reactor.h"
#include <cstdlib>
#include <format>
#include <utility>
Service::~Service() {
for (auto *client : m_clients) {
delete client;
for (auto client : m_clients) {
delete client.second;
}
}
grpc::ServerBidiReactor<chat::chatMsg, chat::chatMsg> *
Service::sendMsg(grpc::CallbackServerContext *context) {
auto newClient = new ChatReactor(this, &m_mu, &m_messages);
m_clients.push_back(newClient);
std::string newId = std::format("user_{}", std::rand());
m_clients.insert(std::make_pair(newId, newClient));
std::cout << "New client: " << newId << std::endl;
return newClient;
}
void Service::sendToAll(const chat::chatMsg &msg) {
for (auto *client : m_clients) {
client->StartWrite(&msg);
std::cout << "Relay message to: ";
for (auto client : m_clients) {
std::cout << client.first << " ";
client.second->StartWrite(&msg);
}
std::cout << std::endl;
}