网络通信线程工作函数:
DWORD CServer::WorkThread( LPVOID param )
{
CServer* pServer = (CServer*)param;
fd_set read_set;
while (true)
{
FD_ZERO(&read_set);
FD_SET(pServer->m_server_socket,&read_set);
for (list<CUser*>::iterator p = pServer->m_users.begin();p != pServer->m_users.end(); ++p)
{
FD_SET((*p)->GetSocket(),&read_set);
}
if (select(0,&read_set,NULL,NULL,NULL) > 0)
{
if(FD_ISSET(pServer->m_server_socket,&read_set))
{ //有连接加入
sockaddr_in addrRemote;
int nAddrLen = sizeof(addrRemote);
SOCKET client_socket = accept(pServer->m_server_socket,(sockaddr*)&addrRemote,&nAddrLen);
if (client_socket)
{ //为客户端分配CUser类
CUser* pUser = new CUser(client_socket);
pServer->m_users.push_back(pUser);
}
}
for (list<CUser*>::iterator p = pServer->m_users.begin();p != pServer->m_users.end(); ++p)
{
www.751com.cn
int ret = (*p)->Recv();
switch(ret)
{
case RECV_ERROR:
{
(*p)->Delete(); //发生异常,删除
break;
}
case RECV_FINISH:
{
(*p)->AnalyseBuffer(); //完成,分析数据包
break;
}
}
}
}
}
}
return 0;
}
接收数据:
int CBuffer::Recv( SOCKET s )
{
if (m_used < 4)
{ //接受数据包头,即数据包大小
int len = recv(s,m_buf + m_used,4 - m_used,0);
if (len == -1)
{
return RECV_ERROR;
}
m_used += len;
if (m_used == 4)
{
int need = GetPackageSize();
if (need <= 0 || need > 512 - 4) //错误的数据包大小
{
return RECV_ERROR;
}
}
}
else
{
int need = GetPackageSize(); //接受数据类型和数据
int len = recv(s,m_buf + m_used,need - m_used + 4,0);
if (len == -1)
{
return RECV_ERROR;
上一页 [1] [2] [3] [4] [5] [6] 下一页