C++中I/O模子之select模子實例。本站提示廣大學習愛好者:(C++中I/O模子之select模子實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C++中I/O模子之select模子實例正文
本文實例講述了C++中I/O模子的select模子用法。分享給年夜家供年夜家參考。詳細完成辦法以下:
void main()
{
CInitSock initSock;
USHORT nPort = 9999; //監聽的端口
SOCKET sListen = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sListen == INVALID_SOCKET)
{
printf("socket error...");
return;
}
sockaddr_in servAddr = {0};
servAddr.sin_family = AF_INET;
servAddr.sin_port = ::htons(nPort);
servAddr.sin_addr.S_un.S_addr = INADDR_ANY;
if (SOCKET_ERROR == ::bind(sListen, (sockaddr*)&servAddr, sizeof(servAddr)))
{
int nError = ::GetLastError();
printf("connect error..");
return;
}
::listen(sListen, 5);
//select模子處置進程
//1.初始化套接字聚集,添加監聽socket到這個聚集
fd_set fdSocket;
FD_ZERO(&fdSocket);
FD_SET(sListen, &fdSocket);
while (TRUE)
{
//2. 將聚集的一個拷貝傳遞給select函數
//當有事宜產生時,select移除未決的socket,然後前往 就是說select前往時 聚集的中socket就是產生事宜的socket
fd_set fdRead = fdSocket;
int nRet = ::select(0, &fdRead, NULL, NULL, NULL);
if (nRet > 0)
{
//經由過程比擬本來的fdSocket聚集與經由處置的fdRead聚集
for (UINT i=0;i<fdSocket.fd_count;i++)
{
if (FD_ISSET(fdSocket.fd_array[i], &fdRead)) //就是這個觸發了
{
if (fdSocket.fd_array[i] == sListen) //監聽套接字吸收到新銜接 為神馬分兩種情形:由於觸發Read聚集的情形有兩種:有銜接來了或數據可讀了....
{
//
if (fdSocket.fd_count < FD_SETSIZE) //FD_SETSIZE=64
{
sockaddr_in addrRemote = {0};
int nAddrLen = sizeof(addrRemote);
SOCKET sNew = ::accept(sListen, (sockaddr*)&addrRemote, &nAddrLen);
FD_SET(sNew, &fdSocket);
}
else
{
printf("too many connection...error");
continue;
}
}
else //有可讀的
{
char szContent[256]={0};
int nRecv = ::recv(fdSocket.fd_array[i], szContent, sizeof(szContent), 0);
if (nRecv > 0)
{
szContent[nRecv] = '\0';
printf("recv data:%s", szContent);
}
else //沒讀到數據
{
::closesocket(fdSocket.fd_array[i]);
FD_CLR(fdSocket.fd_array[i], &fdSocket);
}
}
}
}
}
else
{
printf("nRet litter 0, error...");
return;
}
}
::closesocket(sListen); //與socket配對寫
printf("*******************************");
getchar();
}
後果以下圖所示:
願望本文所述對年夜家的C++法式設計有所贊助。