Files
DesignedWorlds/source/main.c

87 lines
1.9 KiB
C

/* #############################################################################
* # DesingedWorlds
*
*
* AUTHER: PreacherDHM
* DATE: MM/DD/YY
* #############################################################################
*/
#include "http.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void handleClient(int sock) {
while (1) {
int client_sock = accept(sock, NULL, NULL);
if (client_sock < 0) {
perror("accept");
continue;
}
FILE* file = fopen("./web/index.html", "r");
if (file == NULL) {
perror("that file dose not exists");
return;
}
char* fileBuffer;
fseek(file, 0, SEEK_END);
int size = ftell(file);
rewind(file);
printf("file size: %d\n", size);
fileBuffer = (char*)malloc(size + 512);
printf("Sent '%s\n' to the client.\n", fileBuffer);
int bytesRead = fread(fileBuffer, sizeof(char), size, file);
char* response = (char*)malloc(512 + size); // Assuming a maximum length of 512 bytes
HttpResponseHeader* header = createHttpResponse(200, "text/html", fileBuffer, response, 512 + size);
fclose(file);
printf("%s\n", response);
send(client_sock, response, strlen(response)+1, 0);
free(fileBuffer);
}
}
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("socket");
return -1;
}
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(9090);
inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
perror("bind");
return -1;
}
listen(sock, 3);
printf("Server started. Listening on port 9090.\n");
handleClient(sock);
return 0;
}