// we use select instead of creating multiple threads since continuous polling reduces latency
// as specified in the report
//The best way to optimize latency is to use a single thread for handling all requests. This approach eliminates synchronization between threads, and it also eliminates cache misses required to move data between cores in a multithreaded environment.
charbuffer1[1024]={0};
intsd,max_sd;
intcsd,msd;// csd is the client socket descriptor, while msd is the master socket descriptor
intmax_clients=2;
intactivity;
intclient_socket[max_clients-1];
intboth_connected=0,first_time=0;
staticcharbuffer[2*M]={0};
//initialise all client_socket[] to 0 so not checked
for(inti=0;i<max_clients;i++)
{
client_socket[i]=0;
}
//event loop
while(TRUE)
{
//clear the socket set
FD_ZERO(&readfds);
//add master socket to set
FD_SET(server_fd,&readfds);
max_sd=server_fd;
//add child sockets to set
for(inti=0;i<max_clients;i++)
{
//socket descriptor
sd=client_socket[i];
//if valid socket descriptor then add to read list
if(sd>0)
FD_SET(sd,&readfds);
//highest file descriptor number, need it for the select function
if(sd>max_sd)
max_sd=sd;
}
//wait for an activity on one of the sockets , timeout is NULL ,