//接收socket连接线程 void * UdpServer::AcceptThread(void * pParam) { if(0 == pParam) { cout << "param is null." << endl; return 0; } UdpServer * pThis = (UdpServer*)pParam; int maxFd = 0; struct sockaddr_in cliAddr; while(true) { FD_ZERO(&pThis->mReadFd); FD_SET(pThis->mServerSocket, &pThis->mReadFd); maxFd = (pThis->mServerSocket > maxFd)? pThis->mServerSocket : maxFd; for(list<int>::iterator itor = pThis->mCliList.begin(); itor != pThis->mCliList.end(); itor++) { FD_SET(*itor, &pThis->mReadFd); maxFd = (*itor > maxFd)? *itor : maxFd; } int res = select(maxFd + 1, &pThis->mReadFd, 0, 0, NULL); if(-1 == res) { cout << "select failed." << endl; } if(-1 != pThis->mServerSocket && FD_ISSET(pThis->mServerSocket , &pThis->mReadFd)) { int sin_size = sizeof(struct sockaddr_in); int clientSoc = accept(pThis->mServerSocket, (struct sockaddr *)(&cliAddr), (socklen_t*)&sin_size); if(-1 == clientSoc) { cout << "accept error." << endl; continue; } if(DEBUG) cout << "Accept new client : " << clientSoc << endl; pThis->mCliList.push_front(clientSoc); string ip = inet_ntoa(cliAddr.sin_addr); char tmp[16] = {0}; sprintf(tmp, "%d", ntohs(cliAddr.sin_port)); string port = tmp; if(0 != pThis->mAcceptFunc) { pThis->mAcceptFunc(ip, port, clientSoc); } pThis->OnClientConnect(ip, port, clientSoc); } for(list<int>::iterator itor = pThis->mCliList.begin(); itor != pThis->mCliList.end(); itor++) { if(-1 != *itor && FD_ISSET(*itor , &pThis->mReadFd)) { char buf[MAX_MESSAGE_LEN] = {0}; int res = recv(*itor, buf, sizeof(buf), 0); if(0 < res) { if(DEBUG) cout << "Receive data : " << buf << endl; pthread_mutex_lock(&pThis->mMutex); pThis->mDataList.push_back(MsgInfo(*itor, buf)); pthread_mutex_unlock(&pThis->mMutex); } else if(0 == res) { cout << "client quit." << endl; pthread_mutex_lock(&pThis->mMutex); pThis->mCliList.remove(*itor); itor--; pThis->mDisconnectFunc(*itor); pThis->OnClientDisconnect(*itor); pthread_mutex_unlock(&pThis->mMutex); } else { cout << "receive failed." << endl; } } } } }