I'm making a TCP/IP server which listens on multiple ports. I chose to use select to enable handling of multiple events.
So at the moment, i have two sockets, which are connected to two different ports (3000, 3001).
Once I'm inside the select loop, I want the server to respond differently based on the port that it is currently handling. How can I tell what socket I'm on, once inside the select?
I'm adding the code for my selection loop, hopefully you guys can point me in the right direction. Notice that this starts after I've added both file descriptors to the set.
while(1)
{
/* Block until input arrives on one or more active sockets. */
readfds = activefds;
if (select (FD_SETSIZE, &readfds, NULL, NULL, NULL) < 0)
{
perror ("select");
exit (EXIT_FAILURE);
}
/* Service all the sockets with input pending. */
for (i = 0; i < FD_SETSIZE; ++i)
{
if (FD_ISSET (i, &readfds))
{
if (i == S_time)
{
if ((NS = accept(S_time,NULL,NULL)) < 0)
ERROR("server: accept");
开发者_JAVA技巧 FD_SET(NS, &activefds); //add the new socket desc to our active connections set
send_time(NS);
}
else if (i == S_remote)// i == S_remote
{
fprintf(stderr,"Remote");
int status = recieve_request(S_remote);
/* Data arriving on an already-connected socket. */
}
else
{
break;
}
}
} /* //end of for */
} /* //end of while */
So my two sockets are S_time and S_remote. When a client connects to the time socket, I want to send that client the current time. When a client connects to remote, I was want to do remote execution. How can i make this distinction?
Thanks for all your help.
select()
deals with file descriptors, it doesn't know anything about the port number.
You would need to keep track of this information yourself (via a map keyed by the file descriptor, for example) or simply use multiple sets of file descriptors (where each set is specific to a port) and call select
with a zero timeout (non-blocking) on each set.
Check this explanation and sample code, seems that it answers your question. In brief, after select() returns, the corresponding descriptor is included in the corresponding set. For details follow the link.
精彩评论