我在非阻塞套接字(unix下的c語言)中有recv()函數的問題 我已經設置套接字爲非阻塞下面的代碼(服務器程序):socket編程-recv()函數
int x;
x=fcntl(listen_sd,F_GETFL,0);
fcntl(listen_sd,F_SETFL,x | O_NONBLOCK);
當我呼叫recv()
,如果消息可用,它會返回消息的長度,如果沒有,則會阻止!
我起訴了我的代碼中的選擇功能。
while(1)
{
/**********************************************/
/* Receive data on this connection until the */
/* recv fails with EWOULDBLOCK. If any other */
/* failure occurs, we will close the */
/* connection. */
/**********************************************/
rc = recv(i, buffer, sizeof(buffer), 0);
if (rc < 0)
{
if(errno == EAGAIN||errno == EWOULDBLOCK)
{
printf("no message\n");
break;
}
perror(" recv() failed");
close_conn = TRUE;
}
/**********************************************/
/* Check to see if the connection has been */
/* closed by the client */
/**********************************************/
if (rc == 0)
{
printf("connection closed\n");
close_conn = TRUE;
break;
}
/**********************************************/
/* Data was recevied */
/**********************************************/
len = rc;
printf(" %d bytes received\n", len);
}
如果客戶端發送消息並沒有關閉連接,那麼服務器的recv的第一次調用()得到消息,並在第二個呼叫被封鎖(換言之的recv()不返回EWOULDBLOCK錯誤可言!!) 爲什麼?
在這裏使用UDP套接字 – hroptatyr 2012-03-16 10:14:31