From da0d4cc76643292e198f6bfff5fad307f5001bb7 Mon Sep 17 00:00:00 2001 From: anulax1225 Date: Wed, 28 Feb 2024 23:46:21 +0100 Subject: [PATCH] Added an exemple with the simple web server --- src/main.cpp | 68 ++++++++++++++-------------------------------------- 1 file changed, 18 insertions(+), 50 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 06f2706..378aea5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,63 +1,31 @@ #include #include -//C socket includes -#include -#include -#include -#include +#include "bakanet.h" +using namespace Bk::Net; int main() { - int server_fd; - ssize_t valread; - struct sockaddr_in address; - socklen_t addrlen = sizeof(address); - - //Socket creation step - if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) - { - perror("socket failed"); - exit(EXIT_FAILURE); - } + bool running = true; - address.sin_family = AF_INET; - address.sin_addr.s_addr = INADDR_ANY; - address.sin_port = htons(80); - - //Binding step - if (bind(server_fd, (struct sockaddr*)&address, - sizeof(address)) - < 0) - { - perror("bind failed"); - exit(EXIT_FAILURE); - } - - //Listening step - if (listen(server_fd, 3) < 0) - { - perror("listen"); - exit(EXIT_FAILURE); - } + IpAddress ip("127.0.0.1"); + Socket sock(ip, 8080, IpProtocol::TCP); + running = sock.init() && sock.start(50); std::string msg = "HTTP/1.1 200 OK\r\n" - "Content-Type: text/html\r\n\r\n" - "

Hello World!

"; - while (true) - { - int socket; - //Accepting connections step - if ((socket - = accept(server_fd, (struct sockaddr*)&address, - &addrlen)) - > 0) + "Content-Type: text/html\r\n\r\n" + "

Hello World!

"; + std::vector data(msg.begin(), msg.end()); + + while (running) + { + Connection conn; + if ((conn = sock.ack()) > 0) { - //Sending data step - send(socket, msg.c_str(), msg.length(), 0); - close(socket); - } + //Sending data step + sock.write(conn, data); + close(conn); + } } - close(server_fd); return 0; } \ No newline at end of file