Linux下网络socket编程——实现服务器(select)与多个客户端通信(参考的)
Linux编程之select
使用epoll实现一个udp server && client
1. select()使用
int select(int nfds, fd_set *readset, fd_set *writeset, fd_set* exceptset, struct timeval *timeout);
功能:测试指定的fd可读?可写?有异常条件待处理?
参数:nfds,需要检查的文件描述字个数(即检查到fd_set的第几位,提高效率,后面的不检查),数值应该比三组fd_set中所含的最大fd值更大,一般设为三组fd_set中所含的最大fd值加1(如在readset,writeset,exceptset中所含最大的fd为 5,则nfds=6,因为fd是从0开始的)。设这个值是为提高效率,使函数不必检查fd_set的所有1024位。
fd_set的数据结构,实际上是一long类型的数组,每一个数组元素都能与一打开的文件句柄(不管是socket句柄,还是其他文件或命名管道或设备句柄)
fd_set数量被限制,即能监听端口的大小有限。一般来说这个数目和系统内存关系很大,具体数目可以cat/proc/sys/fs/file-max察看。32位机默认是1024个。64位机默认是2048.
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
fd_set set;
int max_fd=1;
struct timeval tv;
while(1)
{
//初始化:超时、fd_set、最大fd值
tv.tv_sec=27;
tv.tv_usec=0;
FD_ZERO(&set);
max_fd=0;
//加入监听的fd
FD_SET(sock_fd, &set); //0:标准输入 1:标准输出 2:标准error
if(max_fd < sock_fd)
{
max_fd = sock_fd;
}
//select多路复用
int ret = select(max_fd + 1, &set, NULL, NULL, &tv);
if(ret < 0)
{
perror("select failure\n");
continue;
}
else if(ret == 0)
{
printf("time out!");
continue;
}
//else{} //为了减少层级,事件处理不放在else里,因为前面两种情况都continue了
//判断set中哪个有事件,逐个轮询
if(FD_ISSET(sock_fd, &set))
{
}
}
return 0;
}
2. epoll()使用
3. IOCP使用
3.1 步骤
- (1) 创建IOCP绑定socket:CreateIoCompletionPort()
- (2) 投递接收请求:WSARecvFrom()
- (3) 获取通道数据:GetQueuedCompletionStatus(),而后重复(3)
- (4) 投递发送请求:WSASendTo()
3.2 IO重叠
int WSARecv(
__in SOCKET s,
__inout LPWSABUF lpBuffers,
__in DWORD dwBufferCount,
__out LPDWORD lpNumberOfBytesRecvd,
__inout LPDWORD lpFlags,
__in LPWSAOVERLAPPED lpOverlapped,
__in LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
int WSASend(
__in SOCKET s,
__in LPWSABUF lpBuffers,
__in DWORD dwBufferCount,
__out LPDWORD lpNumberOfBytesSent,
__in DWORD dwFlags,
__in LPWSAOVERLAPPED lpOverlapped,
__in LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);
WSARecv返回错误10024解决办法:(可能是WSARecv的参数错误)
Bad address. The system detected an invalid pointer address in attempting to use a pointer argument of a call. This error occurs if an application passes an invalid pointer value, or if the length of the buffer is too small. For instance, if the length of an argument, which is a sockaddr structure, is smaller than the sizeof(sockaddr).
网上大致分成两种情况:
1、参数传递错误:将lpFlags字段直接传成了0。
2、lpBuffers需要4字节对齐。
WSARecv 投递缓冲区也要对齐,不然就10014
LPWSABUF lpwsaBuf;
int iAlign = 4;
lpwsaBuf = (LPWSABUF) ((new CHAR[sizeof(WSABUF) + iAlign]) + iAlign); //pOverlapBuff->GetWSABuffer();
lpwsaBuf->buf = new CHAR[52]; //主要是这里,有的说在堆上,不能在栈上
lpwsaBuf->len = 52;
DWORD RecvBytes = 0, Flags = 0;
int ret = WSARecv(m_nFD, lpwsaBuf, 1, &pOlEx->dwBytes, &pOlEx->dwFlags, &pOlEx->ol, nullptr);
(调了好长时间)最终的事实证明是,buf和len没对上,导致10014。原因是取的QVector的指针,makeSpace时括号没对,导致两个不一致(越界)。同时要在CTcpConnection::handleRead中重新投递EnableReading(),也即调用WSARecv()。
//创建流程
CClientDelegate::run();
CTcpClient::Connect();
CConnector::Start();
CConnector::startInDisp();
CConnector::connect();
CSock::Create();
//读流程:
CClientDelegate::run()
CEventDisp::Run();
CChannel::handleEvent()
CChannel::handleEventWithGuard();
CTcpConnection::handleRead(); //调用Delegate的回调,并重新投递EnableReading()
CClientDelegate::onMessage()
//写流程
CClientDelegate::Send(const void* pData,int nLen);
spConn->Send(pData,nLen);
CTcpConnection::Send(const void* pData,int nLen);
m_pDisp->RunInDisp(bind(&bindSendInDisp,this,str));
//压入dsp中,等待事件循环
CClientDelegate::run();
CEventDisp::Run();
CEventDisp::doPendingFuncs();
//在事件循环中调用bindSendInDisp()
CTcpConnection::bindSendInDisp(CTcpConnection* pConn,const QByteArray& str);
CTcpConnection::sendInDisp(const void* pData,quint32 uLen);
CTcpConnection::handleWrite(void* pParam)
m_spChannel->EnableWriting(m_OutputBuffer.Peek(),m_OutputBuffer.ReadableBytes());
CChannel::EnableWriting();
CChannel::postSend();