WHY2/src/chat/main/server.c

68 lines
1.9 KiB
C
Raw Normal View History

2023-02-09 17:19:49 +01:00
/*
This is part of WHY2
Copyright (C) 2022 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <why2/chat/common.h>
2023-02-22 09:56:23 +01:00
#include <unistd.h>
2023-02-21 10:53:09 +01:00
#include <why2/chat/misc.h>
2023-02-09 09:09:26 +01:00
int main(void)
{
int listen_socket = socket(AF_INET, SOCK_STREAM, 0); //CREATE SERVER SOCKET
2023-02-20 18:32:39 +01:00
pthread_t thread;
size_t line_length_buffer = 0;
char *line_buffer = NULL;
2023-02-09 19:18:46 +01:00
if (listen_socket < 0) why2_die("Failed creating socket.");
//DEFINE SERVER ADDRESS
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = INADDR_ANY;
//BIND SOCKET
2023-02-09 19:18:46 +01:00
if (bind(listen_socket, (SA *) &server_addr, sizeof(server_addr)) < 0) why2_die("Failed binding socket.");
//LISTEN
2023-02-09 19:44:55 +01:00
if (listen(listen_socket, MAX_CONNECTIONS) < 0) why2_die("Binding failed.");
2023-02-09 09:09:26 +01:00
2023-02-21 15:05:31 +01:00
printf("Server enabled.\n\n");
2023-02-21 19:48:07 +01:00
pthread_create(&thread, NULL, why2_accept_thread, &listen_socket);
2023-02-09 18:42:23 +01:00
2023-02-22 09:56:23 +01:00
for (;;)
{
getline(&line_buffer, &line_length_buffer, stdin);
if (strcmp(line_buffer, "!exit\n") == 0) //USER REQUESTED PROGRAM EXIT
{
printf("Exiting...\n");
break;
}
}
//DEALLOCATION
why2_clean_threads();
2023-02-22 09:56:23 +01:00
free(line_buffer);
close(listen_socket);
pthread_cancel(thread);
2023-02-20 18:32:39 +01:00
return 0;
2023-02-21 10:53:09 +01:00
}