Additions to test select(), incoplete and w/errors

dev
MasterRoby3 2023-08-10 20:11:45 +02:00
parent 23b42c58fa
commit 11e3f51a3a
1 changed files with 74 additions and 0 deletions

View File

@ -4,10 +4,13 @@
#include <cstdio>
#include <cstdlib>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/time.h>
int makeSocket() {
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
@ -55,6 +58,7 @@ void term_handler(int signal) {
exit(EXIT_SUCCESS);
}
/*
int main(int argc, char const *argv[]) {
signal(SIGTERM, term_handler);
@ -81,5 +85,75 @@ int main(int argc, char const *argv[]) {
}
return 0;
}*/
#define TRUE 1
#define FALSE 0
int main(int argc, char const *argv[]) {
signal(SIGTERM, term_handler);
if (argc != 2) {
printf("Usage: %s portNumber \n", argv[0]);
exit(EXIT_FAILURE);
}
int port = atoi(argv[1]);
printf("Start socket port %d\n", port);
int opt = TRUE;
int master_socket , addrlen , new_socket , client_socket[30] ,
max_clients = 30 , activity, i , valread , sd;
int max_sd;
//set of socket descriptors
fd_set readfds;
//initialise all client_socket[] to 0 so not checked
for (i = 0; i < max_clients; i++)
{
client_socket[i] = 0;
}
master_socket = makeSocket();
//set master socket to allow multiple connections ,
//this is just a good habit, it will work without this
if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt,
sizeof(opt)) < 0 )
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
bindSocketPort(master_socket, port);
startListening(master_socket);
while (true) {
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(master_socket, &readfds);
max_sd = master_socket;
}
int client_fd = acceptConnection(server_fd);
while (true) {
uint32_t word;
ssize_t bytes = read(client_fd, &word, 4);
if (bytes != 4) {
perror("Receive failed");
exit(EXIT_FAILURE);
}
printf("[RICEVUTO]\t0x%x\n", word);
}
return 0;
}