Commit b6da529e by kigrig

Server code upload

parent 7cbe59ae
Showing with 58 additions and 0 deletions
#include "func.h"
#define PORT 20000 // Port, kus avaldakse server
// http://localhost:20000/
int main() {
// Server preperation
int sockfd = socket(AF_INET, SOCK_STREAM, 0); // Luua socket (IPv4, TCP)
if (sockfd == -1) { // Kontroll, kas loomine on õnestus
std::cout << "Failed to create socket. errno: " << errno << std::endl;
exit(EXIT_FAILURE);
}
sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET; // TCP protocol
sockaddr.sin_addr.s_addr = INADDR_ANY; // Struktuur, mis sisaldab IPv4 transpordi aadressi.
sockaddr.sin_port = htons(PORT); // Port, mis edasi kasutame (On andud PORT konstandi)
if (bind(sockfd, (struct sockaddr*)&sockaddr, sizeof(sockaddr)) < 0) { // bindime, ehk
std::cout << "Failed to bind to port " << PORT << ". errno: " << errno << std::endl; // resirveerime
exit(EXIT_FAILURE); // socket
}
// Serveri too
while(true){
if (listen(sockfd, 10) < 0) {
std::cout << "Failed to listen on socket. errno: " << errno << std::endl;
exit(EXIT_FAILURE);
}
// Grab a connection from the queue
auto addrlen = sizeof(sockaddr);
int connection = accept(sockfd, (struct sockaddr*)&sockaddr, (socklen_t*)&addrlen);
if (connection < 0) {
std::cout << "Failed to grab connection. errno: " << errno << std::endl;
exit(EXIT_FAILURE);
}
// Read from the connection
char buffer[4096];
read(connection, buffer, 4096);
struct requestDetails details = splitRequest(buffer); // HTTP paringu osadeks jagamine
if(details.path == "/stop") break; // Paring /stop paneb server kinni
//HTTP paring
//std::cout << "The message was:\n" << buffer << '\n' << '\n';
sendResponse(connection, details);
close(connection);
}
// Close the connections
close(sockfd);
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment