Hello everybody!
I've wrote a very simple echo server, based on a book about LInux socket programming example and it works just fine. My only problem is that i want to use select() function to handle several connections at one time. I've read lots of reference concerning that function and tried several implementations (the one from IBM website and the one from one russian wiki) but they aren't working :(
As far as i understand, to use select() i must create two structures - one for timeout and one for select() internal variables, just like this:
struct timeval timeout;
struct fd_set master_set, working_set;
Then we send our socket to non-blocking mode (using fcntl()).
Then... Well, that's the place i've stuck. Simply could't understand how this should work.
The code now looks like
#include <stdio.h>
#include <sys/socket.h>
#include <resolv.h>
#include <arpa/inet.h>
#include <errno.h>
#include <sys/types.h>
#define MAXBUF 1024
int main(int Count, char *Strings[])
{
int sockfd;
int listen_sd, max_sd, new_sd;
struct sockaddr_in self;
char buffer[MAXBUF];
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
perror("Socket");
exit(errno);
}
memcpy(&self, 0, sizeof(self));
self.sin_family = AF_INET;
self.sin_port = htons(Strings[1]);
self.sin_addr.s_addr = INADDR_ANY;
if ( bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0 )
{
perror("socket--bind");
exit(errno);
}
if ( listen(sockfd, 20) != 0 )
{
perror("socket--listen");
exit(errno);
}
while (1)
{
int clientfd;
struct sockaddr_in client_addr;
int addrlen=sizeof(client_addr);
clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);
printf("%s:%d connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
send(clientfd, buffer, recv(clientfd, buffer, MAXBUF, 0), 0);
close(clientfd);
}
close(sockfd);
return 0;
}
So, i'm calling for help - a good reference, some simple examples, anything would be useful.
Maybe someone will show me the place in this code, where i should place select() and what it's arguments would be.
Of cource the main goal is to learn how to use the function.