use specified port

This commit is contained in:
sfja 2026-04-09 15:29:02 +02:00
parent 3832482cd5
commit 20937d56e6
3 changed files with 12 additions and 11 deletions

View File

@ -9,10 +9,8 @@
#include <sys/types.h> #include <sys/types.h>
#include <thread> #include <thread>
#ifdef BACKEND_TCP_PORT #ifndef BACKEND_TCP_PORT
#define PORT BACKEND_TCP_PORT #define BACKEND_TCP_PORT 8888
#else
#define PORT 8888
#endif #endif
#ifndef BACKEND_MQTT_PORT #ifndef BACKEND_MQTT_PORT
@ -29,7 +27,7 @@ int main(void)
auto mqtt_client = mst::mqtt::Client( auto mqtt_client = mst::mqtt::Client(
BACKEND_MQTT_HOST, BACKEND_MQTT_PORT, "test", "1234"); BACKEND_MQTT_HOST, BACKEND_MQTT_PORT, "test", "1234");
auto server = mst::server::Server(); auto server = mst::server::Server(BACKEND_TCP_PORT);
mqtt_client.subscribe("/skateboard/update", [&](std::string_view text) { mqtt_client.subscribe("/skateboard/update", [&](std::string_view text) {
std::println("Skateboard sent: {}", text); std::println("Skateboard sent: {}", text);

View File

@ -29,7 +29,7 @@ struct Measurement {
double angle; double angle;
}; };
auto get_listener_socket() -> int auto get_listener_socket(const std::string& port) -> int
{ {
int listener; // Listening socket descriptor int listener; // Listening socket descriptor
int status; int status;
@ -41,7 +41,7 @@ auto get_listener_socket() -> int
struct addrinfo* addr; struct addrinfo* addr;
if ((status = ::getaddrinfo(NULL, "8889", &hints, &addr)) != 0) if ((status = ::getaddrinfo(NULL, port.c_str(), &hints, &addr)) != 0)
throw Error(std::format("getaddrinfo ({})", ::gai_strerror(status))); throw Error(std::format("getaddrinfo ({})", ::gai_strerror(status)));
struct addrinfo* p; struct addrinfo* p;
@ -86,15 +86,16 @@ struct Server::State {
std::vector<int> subscriber_fds; std::vector<int> subscriber_fds;
}; };
Server::Server() Server::Server(uint16_t port)
: m_state(std::make_unique<State>()) : m_port(port)
, m_state(std::make_unique<State>())
{ {
} }
Server::~Server() = default; Server::~Server() = default;
void Server::listen() void Server::listen()
{ {
m_listener_fd = get_listener_socket(); m_listener_fd = get_listener_socket(std::to_string(m_port));
m_state->pollfds.push_back(::pollfd { m_state->pollfds.push_back(::pollfd {
.fd = m_listener_fd, .fd = m_listener_fd,
.events = POLLIN, .events = POLLIN,

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <cstdint>
#include <memory> #include <memory>
#include <stdexcept> #include <stdexcept>
@ -11,7 +12,7 @@ struct Error : public std::runtime_error {
class Server { class Server {
public: public:
explicit Server(); explicit Server(uint16_t port);
~Server(); ~Server();
void listen(); void listen();
@ -23,6 +24,7 @@ private:
void create_connection(); void create_connection();
void handle_request(size_t i); void handle_request(size_t i);
uint16_t m_port;
int m_listener_fd { }; int m_listener_fd { };
std::unique_ptr<State> m_state { nullptr }; std::unique_ptr<State> m_state { nullptr };
}; };