中使用輪詢函數的下列代碼存在困惑,下面的代碼是TCP服務器。我對POSIX
bool Run()
{
bool result = false;
m_Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALIDE_SOCKET == m_Socket)
{
printf("Invalide socket...");
return result;
}
sockaddr_in servAddr;
unsigned int sockAddrSize = sizeof(sockaddr_in);
bzero(&servAddr, sockAddrSize);
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(m_Port);
if (0 != bind(m_Socket, (sockaddr *)&servAddr, sockAddrSize))
{
printf("Can not bind socket addres to socket file...\n");
return result;
}
if (0 != listen(m_Socket, MAX_CONNECTION))
{
printf("Can not listen socket...\n");
return result;
}
printf("Server is stared. Please enter any key to continue...\n");
getchar();
system("clear");
m_Listener.Start();
m_DataReader.Start();
sockaddr_in temp;
while (true)
{
bzero(&temp, sockAddrSize);
int tempSocket = accept(m_Socket, (sockaddr *)&temp, &sockAddrSize);
if (-1 == tempSocket)
{
printf("accept is fialed...\n");
}
else
{
printf("A connection is established!\n");
}
//This is my intention:blocking after the client is connected and before the client to be send any data.
//When the client sends data, the program will print '---------------'.
pollfd tempTest;
tempTest.events = POLLRDNORM;
tempTest.revents = 0;
tempTest.fd = tempSocket;
int pollRes = poll(&tempTest, 1, -1);
if (pollRes == 1 && POLLRDNORM == tempTest.revents)
{
printf("-------------------\n");
}
}
return result;
}
事實上,當將客戶端連接到服務器,並且不發送任何數據,下列代碼不符合我的意圖,因爲它沒有被阻塞並且印刷「--------- -----'也:
//This is my intention:blocking after the client is connected and before the client to be send any data.
//When the client sends data, the program will print '---------------'.
pollfd tempTest;
tempTest.events = POLLRDNORM;
tempTest.revents = 0;
tempTest.fd = tempSocket;
int pollRes = poll(&tempTest, 1, -1);
if (pollRes == 1 && POLLRDNORM == tempTest.revents)
{
printf("-------------------\n");
}
這顯然不是你真正的代碼。由於'follfd'沒有被定義,這甚至不會編譯。 – twalberg 2014-09-23 18:21:05
在所有錯誤情況下使用'perror'。 – 2014-09-24 04:15:31