non blocking TCP-acceptor not reading from socket
- by Abruzzo Forte e Gentile
I have the code below implementing a NON-Blocking TCP acceptor. Clients are able to connect without any problem and the writing seems occurring as well, but the acceptor doesn't read anything from the socket and the call to read() blocks indefinitely.
Am I using some wrong setting for the acceptor?
Kind Regards
AFG
int main(){
create_programming_socket();
poll_programming_connect();
while(1){
poll_programming_read();
}
}
int create_programming_socket(){
int cnt = 0;
p_listen_socket = socket( AF_INET, SOCK_STREAM, 0 );
if( p_listen_socket < 0 ){
return 1;
}
int flags = fcntl( p_listen_socket, F_GETFL, 0 );
if( fcntl( p_listen_socket, F_SETFL, flags | O_NONBLOCK ) == -1 ){
return 1;
}
bzero( (char*)&p_serv_addr, sizeof(p_serv_addr) );
p_serv_addr.sin_family = AF_INET;
p_serv_addr.sin_addr.s_addr = INADDR_ANY;
p_serv_addr.sin_port = htons( p_port );
if( bind( p_listen_socket, (struct sockaddr*)&p_serv_addr
, sizeof(p_serv_addr) ) < 0 ) {
return 1;
}
listen( p_listen_socket, 5 );
return 0;
}
int poll_programming_connect(){
int retval = 0;
static socklen_t p_clilen = sizeof(p_cli_addr);
int res = accept( p_listen_socket, (struct sockaddr*)&p_cli_addr, &p_clilen );
if( res > 0 ){
p_conn_socket = res;
int flags = fcntl( p_conn_socket, F_GETFL, 0 );
if( fcntl( p_conn_socket, F_SETFL, flags | O_NONBLOCK ) == -1 ){
retval = 1;
}else{
p_connected = true;
}
}else if( res == -1 && ( errno == EWOULDBLOCK || errno == EAGAIN ) ) {
//printf( "poll_sock(): accept(c_listen_socket) would block\n");
}else{
retval = 1;
}
return retval;
}
int poll_programming_read(){
int retval = 0;
bzero( p_buffer, 256 );
int numbytes = read( p_conn_socket, p_buffer, 255 );
if( numbytes > 0 ) {
fprintf( stderr, "poll_sock(): read() read %d bytes\n", numbytes );
pkt_struct2_t tx_buf;
int fred;
int i;
} else if( numbytes == -1 && ( errno == EWOULDBLOCK || errno == EAGAIN ) ) {
//printf( "poll_sock(): read() would block\n");
} else {
close( p_conn_socket );
p_connected = false;
retval = 1;
}
return retval;
}