using select() to check for data availlability
Posted: Sat Jul 10, 2004 2:55 pm
Hi.
I'm still newbie to socket programming. One of my programs listens on a port, accepts one connection and then, in a loop it checks for data to read with select(). I connect to the socket with telnet, my program prints "accepted connection". When I write data through telnet, select() does not seem to see it.
The dots are never printed.
My connection throuth telnet looks like this:
Weirdly, the following code does respond for the data and puts them on screen.
Oh my this is ain't so easy as it looks ??? I think I should try the poll() call.
Well, now the question.. I would be very grateful if anybody would help me find the error.
Cheers,
Adrian
I'm still newbie to socket programming. One of my programs listens on a port, accepts one connection and then, in a loop it checks for data to read with select(). I connect to the socket with telnet, my program prints "accepted connection". When I write data through telnet, select() does not seem to see it.
Code: Select all
int main()
{
int sfd1, sfd2;
struct sockaddr_in sin1,sin2;
int i;
int rozmiar=sizeof(sin2);
//create a socket
sfd1= socket(AF_INET, SOCK_STREAM, 0);
//bind
sin1.sin_family=AF_INET;
sin1.sin_port=htons(4000);
sin1.sin_addr.s_addr=INADDR_ANY;
i= bind(sfd1, (struct sockaddr*)&sin1, sizeof(sin1));
if (i<0) { printf("bind error\n"); exit(-1); }
//listen at the port
listen(sfd1,1);
//accept one connection
sfd2= accept(sfd1, (struct sockaddr*)&sin2, &rozmiar);
if (sfd2<0) { printf("accept error?\n"); exit(-1); }
printf("accepted\n"); //yup, this one is executed
while (1) {
fd_set r;
FD_ZERO(&r);
FD_SET(sfd2, &r);
struct timeval u;
u.tv_sec=0;
u.tv_usec=100;
i= select(1+1, &r,NULL,NULL, &u);
if (i!=1) continue; //so: continue until "read from the file descriptor would not block"
//it doesn't get to this place ever...
printf(".");fflush(stdout);
}/*while*/
}
My connection throuth telnet looks like this:
Code: Select all
root@ttyp0[knoppix]# telnet localhost 4000
Trying 127.0.0.1...
Connected to Knoppix.
Escape character is '^]'.
f
g
f
g
Code: Select all
while (1) {
char buf[20];
i= recv(sfd2, buf, 19, 0);
buf[i]='\0';
printf("%s", buf);
}/*while*/
Well, now the question.. I would be very grateful if anybody would help me find the error.
Cheers,
Adrian