initial commit
This commit is contained in:
+79
@@ -0,0 +1,79 @@
|
||||
|
||||
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>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
void Handler::Handle(int sock) {
|
||||
std::cout << std::format("Handler {} start", sock) << std::endl;
|
||||
std::chrono::milliseconds timesleep(1s);
|
||||
std::this_thread::sleep_for(timesleep);
|
||||
std::cout << std::format("Handler {} done", sock) << std::endl;
|
||||
close(sock);
|
||||
}
|
||||
|
||||
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(Handler *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(&Handler::Handle, handler, newsock);
|
||||
t.detach();
|
||||
}
|
||||
return {};
|
||||
}
|
||||
Reference in New Issue
Block a user