我有以下代码实现NON-Blocking TCP接受器。客户端能够毫无问题地连接,并且写入似乎也在发生,但是接受器不会从套接字中读取任何内容,并且无限期地调用read()
块。
我对接受者使用了一些错误的设置吗?
亲切的问候 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 );
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;
}
答案 0 :(得分:3)
对poll_programming_connect
的调用超出了你的while循环 - 所以它很可能不接受连接(使用EWOULDBLOCK失败)。所以你没有一个有效的套接字来读取。
在致电poll_programming_read
之前,您需要等到有联系。