79 lines
2.4 KiB
C++
79 lines
2.4 KiB
C++
|
|
extern "C" {
|
|
#include <arpa/inet.h>
|
|
}
|
|
|
|
#include <expected>
|
|
#include <string>
|
|
#include <vector>
|
|
#include <span>
|
|
#include <iostream>
|
|
#include <thread>
|
|
#include <chrono>
|
|
#include <cstring>
|
|
|
|
#include <service.hpp>
|
|
#include <logger.hpp>
|
|
#include <msgheader.hpp>
|
|
|
|
#include <control.pb.h>
|
|
|
|
using namespace std::chrono_literals;
|
|
|
|
void SocketHandler::Handle(int sock) {};
|
|
SocketHandler::~SocketHandler(void) {};
|
|
|
|
Service::Service(int svcport) {
|
|
port = svcport;
|
|
}
|
|
Service::~Service() {
|
|
close(port);
|
|
}
|
|
|
|
std::expected<void, std::string> Service::Bind(void) {
|
|
struct sockaddr_in address;
|
|
int srvsock;
|
|
if ((srvsock = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
|
|
int errnocopy = errno;
|
|
std::string error = std::strerror(errnocopy);
|
|
return std::unexpected("Create socker error: " + error);
|
|
}
|
|
int opt = 1;
|
|
if (setsockopt(srvsock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
|
|
int errnocopy = errno;
|
|
std::string error = std::strerror(errnocopy);
|
|
return std::unexpected("Set socket option error: " + error);
|
|
}
|
|
address.sin_family = AF_INET;
|
|
address.sin_addr.s_addr = INADDR_ANY;
|
|
address.sin_port = htons(port);
|
|
if (bind(srvsock, (struct sockaddr *)&address, sizeof(address)) < 0) {
|
|
int errnocopy = errno;
|
|
std::string error = std::strerror(errnocopy);
|
|
return std::unexpected("Bind error: " + error);
|
|
}
|
|
if (listen(srvsock, 3) < 0) {
|
|
int errnocopy = errno;
|
|
std::string error = std::strerror(errnocopy);
|
|
return std::unexpected("Listen error: " + error);
|
|
}
|
|
sock = srvsock;
|
|
return {};
|
|
}
|
|
|
|
std::expected<void, std::string> Service::Listen(SocketHandler *handler) {
|
|
struct sockaddr_in address;
|
|
int addrlen = sizeof(address);
|
|
int newsock = 0;
|
|
for (;;) {
|
|
if ((newsock = accept(sock, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
|
|
int errnocopy = errno;
|
|
std::string error = std::strerror(errnocopy);
|
|
return std::unexpected("Accept error: " + error);
|
|
}
|
|
std::jthread t(&SocketHandler::Handle, handler, newsock);
|
|
t.detach();
|
|
}
|
|
return {};
|
|
}
|