Select模型
来自:http://blog.csdn.net/dylgsy/archive/2007/01/18/查找了很多资料都找不到select模型的详细用法,《Windows网络编程》这本书上也只是写了一个简单的回应服务器,就连writefds的用法都没讲,也不知道什么时候利用“可写”来发文件。这些都是我的疑问,相信很多研究网络编程的同路人也碰到了我的这些问题。这些疑问在这篇文章中都解决了!耗费了偶很多的精力去猜测去思考!
感觉一些已经得道的高人都不肯把这些问题说透彻点,唉,只能靠自己去摸索了,希望这篇文章能对你有用,也希望一些高人能出来指点指点!
SOCKET模型的出现是为了解决“一个客户端一线程”的问题,为了WINDOWS的线程切换不要太频繁,我们可以使用WINDOWS的SOCKET模型。但在论坛里又看到了一些文章说现在的计算机硬件相当发达,成万的线程切换根本不是什么问题。无论怎么样,既然这些模型被MS发明了出来,就有它的道理,我们还是好好来学习一下吧。
对于select模型,大家都知道用select函数,然后判断读集、写集。但如何使用select,最终写好的Server又是一个怎么样的结构呢?
select可以这样用,写成两个函数,SelectSend和SelectRecv,这两个函数和一般的send\recv不同的地方在于它是有超时值的,这样就不会把程序完全阻塞了。这两个函数大概如下(参考《PC网络游戏编程》):
SelectRecv(...)
<div style="padding-right: 5.4pt; padding-left: 5.4pt; background: #e6e6e6; padding-bottom: 4px; width: 95%; padding-top: 4px;">http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gifint SelectRecv(SOCKET hSocket, char *pszBuffer, int nBufferSize,
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif DWORD dwTimeout)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gifhttp://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif...{
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif ASSERT(hSocket != NULL);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif if(hSocket==NULL)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif return ( SOCKET_ERROR );
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gifhttp://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif FD_SET fd = ...{1, hSocket};
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gifhttp://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif TIMEVAL tv = ...{dwTimeout, 0};
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif int nBytesReceived=0;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif if(select(0, &fd, NULL, NULL, &tv) == 0)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif goto CLEAR;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif if((nBytesReceived = recv(hSocket, pszBuffer, nBufferSize, 0)) == SOCKET_ERROR)
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif goto CLEAR;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif return nBytesReceived;
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gifCLEAR:
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif SetLastError(WSAGetLastError());//超时
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif return(SOCKET_ERROR);
http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif}
页:
[1]