working commit
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
|
||||
extern "C" {
|
||||
#include <arpa/inet.h>
|
||||
}
|
||||
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
|
||||
#include <tservice.hpp>
|
||||
#include <uxlogger.hpp>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
TCPService::TCPService(int svcport) {
|
||||
port = svcport;
|
||||
}
|
||||
|
||||
TCPService::~TCPService() {
|
||||
close(port);
|
||||
}
|
||||
|
||||
std::expected<void, std::string> TCPService::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> TCPService::Listen(void) {
|
||||
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(&TCPService::Handle, this, newsock);
|
||||
t.detach();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
void TCPService::Handle(int sock) {
|
||||
uxlogger.Log("Start socker handler");
|
||||
SocketHandler handler;
|
||||
handler.Handle(sock);
|
||||
uxlogger.Log("Stop socker handler");
|
||||
close(sock);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user