Exemple #1
0
void SocketListener1::sendData(const void *data, int len) {
  SocketClientCollection safeList;

  /* Add all active clients to the safe list first */
  safeList.clear();
  pthread_mutex_lock(&mClientsLock);
  SocketClientCollection::iterator i;

  for (i = mClients->begin(); i != mClients->end(); ++i) {
    SocketClient* c = *i;
    c->incRef();
    safeList.push_back(c);
  }
  pthread_mutex_unlock(&mClientsLock);

  while (!safeList.empty()) {
    /* Pop the first item from the list */
    i = safeList.begin();
    SocketClient* c = *i;
    safeList.erase(i);
    if (c->sendData(data, len)) {
      ALOGW("Error sending data (%s)", strerror(errno));
    }
    c->decRef();
    // Release socket client on socket disconnect
    if (errno == EPIPE) {
      ALOGW("Socket disconnect; closing");
      release(c, false);
    }
  }
}
Exemple #2
0
bool HttpServer::methodPost(const SocketClient &client) {
	std::string content;
	if (StringConverter::getContentFrom(client.getMessage(), content)) {
		std::string file;
		if (StringConverter::getRequestedFile(client.getMessage(), file)) {
			if (file.compare("/data.xml") == 0) {
				// not used yet
			} else if (file.compare("/streams.xml") == 0) {
				_streams.fromXML(content);
			} else if (file.compare("/config.xml") == 0) {
				_properties.fromXML(content);
#ifdef LIBDVBCSA
			} else if (file.compare("/dvbapi.xml") == 0) {
				_streams.getDecrypt()->fromXML(content);
#endif
			}
		}
	}
	// setup reply
	std::string htmlBody;
	getHtmlBodyWithContent(htmlBody, HTML_NO_RESPONSE, "", CONTENT_TYPE_HTML, 0, 0);

	// send 'htmlBody' to client
	if (send(client.getFD(), htmlBody.c_str(), htmlBody.size(), 0) == -1) {
		PERROR("send htmlBody");
		return false;
	}
	return true;
}
inline
int
SocketRegistry<T>::syncPerformReceive(char * host,
                                      T & t,
                                      Uint32 timeOutMillis) {
    char buf[255] ; //temp. just for testing. must fix better
    struct timeval timeout;
    timeout.tv_sec  = timeOutMillis / 1000;
    timeout.tv_usec = (timeOutMillis % 1000) * 1000;
    int reply;
    SocketClient * sc;
    for(Uint32 i=0; i < m_nSocketClients; i++) {
        sc = m_socketClients[i];
        if(strcmp(sc->gethostname(), remotehost)==0) {
            if(sc->isConnected()) {
                FD_ZERO(&tcpReadset);
                reply = select(sc->getSocket(), &tcpReadset, 0, 0, &timeout);
                if(reply > 0) {
                    return t->runSession(sc->getSocket(), t);
                }
            }

        }
    }
    return 0;
}
void SocketListener::sendBroadcast(int code, const char *msg, bool addErrno) {
    SocketClientCollection safeList;

    /* Add all active clients to the safe list first */
    safeList.clear();
    pthread_mutex_lock(&mClientsLock);
    SocketClientCollection::iterator i;

    for (i = mClients->begin(); i != mClients->end(); ++i) {
        SocketClient* c = *i;
        c->incRef();
        safeList.push_back(c);
    }
    pthread_mutex_unlock(&mClientsLock);

    while (!safeList.empty()) {
        /* Pop the first item from the list */
        i = safeList.begin();
        SocketClient* c = *i;
        safeList.erase(i);
        // broadcasts are unsolicited and should not include a cmd number
        if (c->sendMsg(code, msg, addErrno, false)) {
            SLOGW("Error sending broadcast (%s)", strerror(errno));
        }
        c->decRef();
    }
}
Exemple #5
0
/**< 跟第三方系统进行通信 */
int CTradeBase::DoSendAndRcv(unsigned char *ReqBuf, int ReqLen,unsigned char *RepBuf, int *RepLen, int TimeOut,char* errDesc)
{
    trace_log(DBG, "SndBuf len:%d",ReqLen);
    trace_mem(ReqBuf, ReqLen);
    SocketClient client;
    return client.SendToHost(ReqBuf,ReqLen,RepBuf,*RepLen,g_Cfg.CupHost.cIp,g_Cfg.CupHost.iPort,40,errDesc);
}
Exemple #6
0
    int  open_connection        (const String &config, const String &display)
    {
        SocketAddress addr (scim_get_default_panel_socket_address (display));

        if (m_socket.is_connected ()) close_connection ();

        bool ret;
        int count = 0;

        // Try three times.
        while (1) {
            if ((ret = m_socket.connect (addr)) == false) {
                scim_usleep (100000);
                launch_panel (config, display);
                for (int i = 0; i < 200; ++i) {
                    if (m_socket.connect (addr)) {
                        ret = true;
                        break;
                    }
                    scim_usleep (100000);
                }
            }
 
            if (ret && scim_socket_open_connection (m_socket_magic_key, String ("FrontEnd"), String ("Panel"), m_socket, m_socket_timeout))
                break;

            m_socket.close ();

            if (count++ >= 3) break;

            scim_usleep (100000);
        }

        return m_socket.get_id ();
    }
Exemple #7
0
void SocketClient::dataCallback(int, unsigned int flags, void* userData)
{
    SocketClient* client = reinterpret_cast<SocketClient*>(userData);
    if (flags & EventLoop::Read)
        client->readMore();
    if (flags & EventLoop::Write)
        client->writeMore();
}
DWORD WINAPI ClientIOCP::WorkerThread(LPVOID lpObject)
{
	SocketClient client;
	char* reply;

	int res = client.Connect(8085);
	client.Send("This is a test\n", reply);
	return 1;
}
inline
int 
SocketRegistry<T>::pollSocketClients(Uint32 timeOutMillis) {



  // Return directly if there are no TCP transporters configured
  if (m_nSocketClients == 0){
    tcpReadSelectReply = 0;
    return 0;
  }
  struct timeval timeout;
  timeout.tv_sec  = timeOutMillis / 1000;
  timeout.tv_usec = (timeOutMillis % 1000) * 1000;


  NDB_SOCKET_TYPE maxSocketValue = 0;
  
  // Needed for TCP/IP connections
  // The read- and writeset are used by select
  
  FD_ZERO(&tcpReadset);

  // Prepare for sending and receiving
  for (Uint32 i = 0; i < m_nSocketClients; i++) {
    SocketClient * t = m_socketClients[i];
    
    // If the socketclient is connected
    if (t->isConnected()) {
      
      const NDB_SOCKET_TYPE socket = t->getSocket();
      // Find the highest socket value. It will be used by select
      if (socket > maxSocketValue)
	maxSocketValue = socket;
      
      // Put the connected transporters in the socket read-set 
      FD_SET(socket, &tcpReadset);
    }
  }
  
  // The highest socket value plus one
  maxSocketValue++; 
  
  tcpReadSelectReply = select(maxSocketValue, &tcpReadset, 0, 0, &timeout);  
#ifdef NDB_WIN32
  if(tcpReadSelectReply == SOCKET_ERROR)
  {
    NdbSleep_MilliSleep(timeOutMillis);
  }
#endif

  return tcpReadSelectReply;

}
Exemple #10
0
/**< 跟第三方系统进行通信 */
int CTradeBase::DoSendAndRcv(unsigned char *ReqBuf, int ReqLen,unsigned char *RepBuf, int *RepLen, int TimeOut,char* errDesc)
{
    trace_log(DBG, "SndBuf len:%d",ReqLen);
    trace_mem(ReqBuf, ReqLen);
#ifndef USE_LONG_CONN
    SocketClient client;
    return client.SendToHost(ReqBuf,ReqLen,RepBuf,*RepLen,g_Cfg.CupHost[0].Host,g_Cfg.CupHost[0].Port,40,errDesc);
#else
	return 0;
#endif
}
int _tmain(int argc, _TCHAR* argv[])
{
	SocketClient so = SocketClient("192.168.0.179");
	so.sendTo("Hello from C++  111");
	so.sendTo("Hello from C++  222");
	so.~SocketClient();

	/*WSAData data;
	SOCKET sock;
	struct sockaddr_in si_other;
	const std::string address = "192.168.0.179";
	int slen = sizeof(si_other);
	char message[512] = "Hello World Java, I am a C++ Client Socket";

	int ret = WSAStartup(MAKEWORD(2, 2), &data);
	if (ret != 0) {
		printf("Error WSAStartup failed: " + WSAGetLastError());
		WSACleanup();
	}

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if (sock == INVALID_SOCKET) {
		printf("Error opening socket: " + WSAGetLastError());
	}

	memset((char *)&si_other, 0, sizeof(si_other));
	si_other.sin_family = AF_INET;
	si_other.sin_port = htons(8881);
	si_other.sin_addr.S_un.S_addr = inet_addr(address.c_str());
	
	std::stringstream sstm;
	for (int i = 0; i < 10; i++) {
		sstm << "Attemp #" << i << " - Sending:" << message << "\n";
		printf(sstm.str().c_str());
		ret = sendto(sock, message, strlen(message), 0, (struct sockaddr *) &si_other, slen);
		if (ret < 0) {
			sstm << "Failed Sending:" << WSAGetLastError();
		}
		sstm.str("");
	}

	printf("\n *** End ***");
	std::getchar();
	exit(0);

	closesocket(sock);
	WSACleanup();  */

	return 0;
}
bool
SocketRegistry<T>::reconnect(const char * host) {
    for(Uint32 i=0; i < m_nSocketClients; i++) {
        SocketClient * socketClient = m_socketClients[i];
        if(strcmp(socketClient->gethostname(), host)==0) {
            if(!socketClient->isConnected()) {
                if(socketClient->openSocket() > 0)
                    return true;
                else return false;
            }
        }
    }
    return false;
}
Exemple #13
0
    bool prepare                (int icid)
    {
        if (!m_socket.is_connected ()) return false;

        int cmd;
        uint32 data;

        if (m_send_refcount <= 0) {
            m_current_icid = icid;
            m_send_trans.clear ();
            m_send_trans.put_command (SCIM_TRANS_CMD_REQUEST);
            m_send_trans.put_data (m_socket_magic_key);
            m_send_trans.put_data ((uint32) icid);

            m_send_trans.get_command (cmd);
            m_send_trans.get_data (data);
            m_send_trans.get_data (data);
            m_send_refcount = 0;
        }

        if (m_current_icid == icid) {
            m_send_refcount ++;
            return true;
        }
        return false;
    }
int
SocketRegistry<T>::performReceive(T & t) {
    char buf[255] ; //temp. just for testing. must fix better

    if(tcpReadSelectReply > 0) {
        for (Uint32 i=0; i<m_nSocketClients; i++) {
            SocketClient *sc = m_socketClients[i];
            const NDB_SOCKET_TYPE socket    = sc->getSocket();
            if(sc->isConnected() && FD_ISSET(socket, &tcpReadset)) {
                t->runSession(socket,t);
            }
        }
        return 1;
    }
    return 0;

}
Exemple #15
0
inline
bool 
SocketRegistry<T>::removeSocketClient(const char * host){
  for(Uint32 i=0; i < m_nSocketClients; i++) {
    SocketClient * socketClient = m_socketClients[i];
    if(strcmp(socketClient->gethostname(), host)==0) {
      if(!socketClient->isConnected()) {
	if(socketClient->closeSocket() > 0) {
	  delete socketClient;
	  return true;
	}
	else return false;
      }
    }
  }
  return false;
}
Exemple #16
0
inline
bool 
SocketRegistry<T>::performSend(const char * buf, Uint32 len, const char * remotehost)
{
  SocketClient * socketClient;
  for(Uint32 i=0; i < m_nSocketClients; i++) {
    socketClient = m_socketClients[i];
    if(strcmp(socketClient->gethostname(), remotehost)==0) {
      if(socketClient->isConnected()) {
	if(socketClient->writeSocket(buf, len)>0)
	  return true;
	else
	  return false;
      }
    }
  }
  return false;
}
void sendFacialExpressionAnimation(SocketClient& sock, EmoStateHandle eState) {

	std::ostringstream output;

    IEE_FacialExpressionAlgo_t upperFaceType =
                            IS_FacialExpressionGetUpperFaceAction(eState);
    IEE_FacialExpressionAlgo_t lowerFaceType =
                            IS_FacialExpressionGetLowerFaceAction(eState);

	float upperFaceAmp = IS_FacialExpressionGetUpperFaceActionPower(eState);
	float lowerFaceAmp = IS_FacialExpressionGetLowerFaceActionPower(eState);

	if (IS_FacialExpressionIsBlink(eState)) {
		output << "B,";
	}

	if (IS_FacialExpressionIsLeftWink(eState)) {
		output << "l,";
	}

	if (IS_FacialExpressionIsRightWink(eState)) {
		output << "r,";
	}


	if (upperFaceAmp > 0.0) {
		switch (upperFaceType) {
			case FE_SURPRISE:	output << "b";	break;
			case FE_FROWN:    output << "f";  break;
			default:			break;
		}
		output << numberToString(static_cast<int>(upperFaceAmp*100.0f)) << ",";
	}

	if (lowerFaceAmp > 0.0) {
		switch (lowerFaceType) {
			case FE_CLENCH:	output << "G";	break;
			case FE_SMILE:		output << "S";	break;
			default:			break;
		}
		output << numberToString(static_cast<int>(lowerFaceAmp*100.0f)) << ",";
	}

	std::string outString = output.str();

	// Remove the last comma
	if (outString.length()) {
		outString.resize(outString.length()-1);
	}

	if (!outString.length()) {
		outString = std::string("neutral");
	}

	sock.SendBytes(outString);
}
Exemple #18
0
/**************************************************************
函数名称: GetDataFromHsm
函数功能: 连接加密机从其获取数据
入口参数: pMsgBuffer[in/out]:发送或返回的数据中的MSG
           iLen[in/out]:发送或返回数据的长度
相关调用:
返 回 值: true成功, false失败
**************************************************************/
bool EnCryptComm::GetDataFromHsm(unsigned char *pMsgBuffer, unsigned & iLen)
{
    unsigned char cmd = pMsgBuffer[0], Buffer[1024]={0};
    unsigned sLen;//发送数据长度
    sLen = iLen + 7;
    memcpy(Buffer, &sLen, 2);//LC
    Buffer[2]=0xF1;//INS
    Buffer[3]=0;//SEQ
    //CR默认为0
    memcpy(&Buffer[6], pMsgBuffer, iLen);//MSG
    Buffer[sLen-1] = CalcSum(Buffer, sLen - 1);//CRC
    char errDesc[512]={0};
    unsigned char cRecBuf[1024]={0};
    int recLen=0;
    SocketClient client;
    int iErrorCode=client.SendToHost(Buffer,sLen,cRecBuf,recLen,g_Cfg.EncHost.Host, g_Cfg.EncHost.Port,20,errDesc);
    if(0==iErrorCode)
    {
    	trace_log(DBG, "recv from enchost");
		trace_mem(cRecBuf, recLen);
        if(cRecBuf[recLen-1] == CalcSum(cRecBuf, recLen - 1) && cRecBuf[6] == cmd && cRecBuf[8] == CMD_OK)
        {//校验值正确,与原命令字相同,返回码为成功
            if(memcmp(pMsgBuffer+2, cRecBuf+9, LEN_MERCHNO+LEN_TERMINO)!=0)//+LEN_TERMINO
            {//比较商户号与终端号
                trace_log(DBG, "The return data from encryptor is not match!!");
                return false;
            }
            memcpy(pMsgBuffer, cRecBuf+6, recLen-7);//去掉LC,INS,SEQ,CR,CRC
            iLen = recLen-7;
            trace_log(DBG,"GetDataFromHsm->iLen=%d",iLen);
            return true;
        }
        else
        {
            trace_log(ERR, "GetDataFromHsm else CalcSum  %d", recLen);
            return false ;
        }
    }else{
        trace_log(ERR,errDesc);
        return false;
    }
}
Exemple #19
0
void *SocketClient::ReceiveThread(void *para) {
	SocketClient *socketClient = (SocketClient *) para;
	int res;
	while (1) {
		res = recv(socketClient->clientSockFd, socketClient->recvMessage, BUFFER_SIZE, 0);
		if (res == 0) {
			close(socketClient->clientSockFd);
			socketClient->clientSockFd = -1;
			socketClient->pUpdateStauts(Disconnected);
			break;
		}else if(res > 0){
			socketClient->pUpdateMessage(socketClient->recvMessage, res);
		}else{
			perror("receive error");
		}

	}
	printf("Server Closed\n");
	return 0;
}
bool
SocketRegistry<T>::createSocketClient(const char * host, Uint16 port) {

    if(port == 0)
        return false;
    if(host==NULL)
        return false;

    SocketClient * socketClient = new SocketClient(host, port);

    if(socketClient->openSocket() < 0 || socketClient == NULL) {
        ndbout << "could not connect" << endl;
        delete socketClient;
        return false;
    }
    else {
        m_socketClients[m_nSocketClients] = socketClient;
        m_nSocketClients++;
    }
    return true;
}
Exemple #21
0
bool check_socket_frontend ()
{
    SocketAddress address;
    SocketClient client;

    uint32 magic;

    address.set_address (scim_get_default_socket_frontend_address ());

    if (!client.connect (address))
        return false;

    if (!scim_socket_open_connection (magic,
                                      String ("ConnectionTester"),
                                      String ("SocketFrontEnd"),
                                      client,
                                      1000)) {
        return false;
    }

    return true;
}
Exemple #22
0
const void Who::Run( Character* character, const string& cmd, const string& arg ) const
{
    CITER( vector, SocketClient*, si );
    SocketClient* target = NULL;

    if ( character )
    {
        character->Send( CFG_STR_VERSION CRLF );
        for ( si = socket_client_list.begin(); si != socket_client_list.end(); si++ )
        {
            target = *si;

            if ( target->gAccount() == NULL )
                continue;
            if ( target->gAccount()->gCharacter() == NULL )
                continue;
            character->Send( "    " + target->gAccount()->gCharacter()->gName() + CRLF );
        }
    }

    return;
}
void LogTimeEntry::threadStop(void *obj) {
    LogTimeEntry *me = reinterpret_cast<LogTimeEntry *>(obj);

    lock();

    if (me->mNonBlock) {
        me->error_Locked();
    }

    SocketClient *client = me->mClient;

    if (me->isError_Locked()) {
        LogReader &reader = me->mReader;
        LastLogTimes &times = reader.logbuf().mTimes;

        LastLogTimes::iterator it = times.begin();
        while(it != times.end()) {
            if (*it == me) {
                times.erase(it);
                me->release_Locked();
                break;
            }
            it++;
        }

        me->mClient = NULL;
        reader.release(client);
    }

    if (client) {
        client->decRef();
    }

    me->threadRunning = false;
    me->decRef_Locked();

    unlock();
}
Exemple #24
0
void sendCognitivAnimation(SocketClient& sock, EmoStateHandle eState) {

	std::ostringstream os;

	EE_CognitivAction_t actionType	= ES_CognitivGetCurrentAction(eState);
	float				actionPower = ES_CognitivGetCurrentActionPower(eState);
	int					intType = static_cast<int>(actionType);
	int					intPower = static_cast<int>(actionPower*100.0f);

	os << intType << "," << intPower;
	std::cout << os.str()<< std::endl;

	sock.SendBytes(os.str());
}
Exemple #25
0
DWORD Worker::ClientConnThreadProc(void* p)
{
	Worker* pThis = (Worker*)p;

	bOrderEnd = false;
	int nError;

	pThis->m_pSocket = new SocketClient();
	SocketClient* pSocketClient = (SocketClient*)pThis->m_pSocket;

	//TODO: move this in Send / Receive Files Thread
	//pThis->m_dataTransferer.SetSocket(pThis->m_pSocket);

	nError = pSocketClient->Create();
	if (nError)
	{
		DisplayError(nError);
		bOrderEnd = 1;
		goto final;
	}

	SendMessage(MainDlg::m_hStatusText, WM_SETTEXT, 0, (LPARAM)L"Connecting to the server...");

try_again:
	nError = pSocketClient->Connect(14147);//was: 14148
	if (nError && !bOrderEnd)
	{
		if (nError == WSAECONNREFUSED) {Sleep(200); goto try_again;}
		if (nError != WSAETIMEDOUT)
		{
			DisplayError(nError);
			bOrderEnd = 1;
			goto final;
		}
		else
		{
void SocketListener::runOnEachSocket(SocketClientCommand *command) {
    SocketClientCollection safeList;

    /* Add all active clients to the safe list first */
    safeList.clear();
    pthread_mutex_lock(&mClientsLock);
    SocketClientCollection::iterator i;

    for (i = mClients->begin(); i != mClients->end(); ++i) {
        SocketClient* c = *i;
        c->incRef();
        safeList.push_back(c);
    }
    pthread_mutex_unlock(&mClientsLock);

    while (!safeList.empty()) {
        /* Pop the first item from the list */
        i = safeList.begin();
        SocketClient* c = *i;
        safeList.erase(i);
        command->runSocketCommand(c);
        c->decRef();
    }
}
Exemple #27
0
    bool send                   ()
    {
        if (!m_socket.is_connected ()) return false;

        if (m_send_refcount <= 0) return false;

        m_send_refcount --;

        if (m_send_refcount > 0) return false;

        if (m_send_trans.get_data_type () != SCIM_TRANS_DATA_UNKNOWN)
            return m_send_trans.write_to_socket (m_socket, 0x4d494353);

        return false;
    }
void MainLayer::menuCloseCallback(Object* pSender)
{
	SocketClient* socketClient = SocketClient::createSocketClient("127.0.0.1",12345);
	socketClient->retain();
	SocketMgr::set(socketClient);

	socketClient = SocketMgr::get();

	auto callback = std::bind(&MainLayer::onLoginResponse,this,std::placeholders::_1);
	socketClient->registCallbackT<LoginResponse>(1,callback);

	if (socketClient->connect())
	{
		LoginRequest* loginRequestMessage = new LoginRequest();
		loginRequestMessage->set_username("cmzx3444");
		loginRequestMessage->set_password("123456");
		socketClient->send(loginRequestMessage);

		loginRequestMessage = new LoginRequest();
		loginRequestMessage->set_username("cmzx3444");
		loginRequestMessage->set_password("123456");
		socketClient->send(loginRequestMessage);

		loginRequestMessage = new LoginRequest();
		loginRequestMessage->set_username("cmzx3444");
		loginRequestMessage->set_password("123456");
		socketClient->send(loginRequestMessage);

		loginRequestMessage = new LoginRequest();
		loginRequestMessage->set_username("cmzx3444");
		loginRequestMessage->set_password("123456");
		socketClient->send(loginRequestMessage);
	}
	else
	{
		socketClient->release();
	}

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
void SocketListener::runListener() {

    SocketClientCollection pendingList;

    while(1) {
        SocketClientCollection::iterator it;
        fd_set read_fds;
        int rc = 0;
        int max = -1;

        FD_ZERO(&read_fds);

        if (mListen) {
            max = mSock;
            FD_SET(mSock, &read_fds);
        }

        FD_SET(mCtrlPipe[0], &read_fds);
        if (mCtrlPipe[0] > max)
            max = mCtrlPipe[0];

        pthread_mutex_lock(&mClientsLock);
        for (it = mClients->begin(); it != mClients->end(); ++it) {
            // NB: calling out to an other object with mClientsLock held (safe)
            int fd = (*it)->getSocket();
            FD_SET(fd, &read_fds);
            if (fd > max) {
                max = fd;
            }
        }
        pthread_mutex_unlock(&mClientsLock);
        SLOGV("mListen=%d, max=%d, mSocketName=%s", mListen, max, mSocketName);
        if ((rc = select(max + 1, &read_fds, NULL, NULL, NULL)) < 0) {
            if (errno == EINTR)
                continue;
            SLOGE("select failed (%s) mListen=%d, max=%d", strerror(errno), mListen, max);
            sleep(1);
            continue;
        } else if (!rc)
            continue;

        if (FD_ISSET(mCtrlPipe[0], &read_fds)) {
            char c = CtrlPipe_Shutdown;
            TEMP_FAILURE_RETRY(read(mCtrlPipe[0], &c, 1));
            if (c == CtrlPipe_Shutdown) {
                break;
            }
            continue;
        }
        if (mListen && FD_ISSET(mSock, &read_fds)) {
            sockaddr_storage ss;
            sockaddr* addrp = reinterpret_cast<sockaddr*>(&ss);
            socklen_t alen;
            int c;

            do {
                alen = sizeof(ss);
                c = accept(mSock, addrp, &alen);
                SLOGV("%s got %d from accept", mSocketName, c);
            } while (c < 0 && errno == EINTR);
            if (c < 0) {
                SLOGE("accept failed (%s)", strerror(errno));
                sleep(1);
                continue;
            }
            fcntl(c, F_SETFD, FD_CLOEXEC);
            pthread_mutex_lock(&mClientsLock);
            mClients->push_back(new SocketClient(c, true, mUseCmdNum));
            pthread_mutex_unlock(&mClientsLock);
        }

        /* Add all active clients to the pending list first */
        pendingList.clear();
        pthread_mutex_lock(&mClientsLock);
        for (it = mClients->begin(); it != mClients->end(); ++it) {
            SocketClient* c = *it;
            // NB: calling out to an other object with mClientsLock held (safe)
            int fd = c->getSocket();
            if (FD_ISSET(fd, &read_fds)) {
                pendingList.push_back(c);
                c->incRef();
            }
        }
        pthread_mutex_unlock(&mClientsLock);

        /* Process the pending list, since it is owned by the thread,
         * there is no need to lock it */
        while (!pendingList.empty()) {
            /* Pop the first item from the list */
            it = pendingList.begin();
            SocketClient* c = *it;
            pendingList.erase(it);
            /* Process it, if false is returned, remove from list */
            if (!onDataAvailable(c)) {
                release(c, false);
            }
            c->decRef();
        }
    }
}
void SocketListener::runListener() {

    SocketClientCollection *pendingList = new SocketClientCollection();

    while(1) {
        SocketClientCollection::iterator it;
        fd_set read_fds;
        int rc = 0;
        int max = -1;

        FD_ZERO(&read_fds);

        if (mListen) {
            max = mSock;
            FD_SET(mSock, &read_fds);
        }

        FD_SET(mCtrlPipe[0], &read_fds);
        if (mCtrlPipe[0] > max)
            max = mCtrlPipe[0];

        pthread_mutex_lock(&mClientsLock);
        for (it = mClients->begin(); it != mClients->end(); ++it) {
            int fd = (*it)->getSocket();
            FD_SET(fd, &read_fds);
            if (fd > max)
                max = fd;
        }
        pthread_mutex_unlock(&mClientsLock);

        if ((rc = select(max + 1, &read_fds, NULL, NULL, NULL)) < 0) {
            if (errno == EINTR)
                continue;
            SLOGE("select failed (%s)", strerror(errno));
            sleep(1);
            continue;
        } else if (!rc)
            continue;

        if (FD_ISSET(mCtrlPipe[0], &read_fds))
            break;
        if (mListen && FD_ISSET(mSock, &read_fds)) {
            struct sockaddr addr;
            socklen_t alen;
            int c;

            do {
                alen = sizeof(addr);
                c = accept(mSock, &addr, &alen);
            } while (c < 0 && errno == EINTR);
            if (c < 0) {
                SLOGE("accept failed (%s)", strerror(errno));
                sleep(1);
                continue;
            }
            pthread_mutex_lock(&mClientsLock);
            mClients->push_back(new SocketClient(c));
            pthread_mutex_unlock(&mClientsLock);
        }

        /* Add all active clients to the pending list first */
        pendingList->clear();
        pthread_mutex_lock(&mClientsLock);
        for (it = mClients->begin(); it != mClients->end(); ++it) {
            int fd = (*it)->getSocket();
            if (FD_ISSET(fd, &read_fds)) {
                pendingList->push_back(*it);
            }
        }
        pthread_mutex_unlock(&mClientsLock);

        /* Process the pending list, since it is owned by the thread,
         * there is no need to lock it */
        while (!pendingList->empty()) {
            /* Pop the first item from the list */
            it = pendingList->begin();
            SocketClient* c = *it;
            pendingList->erase(it);
            /* Process it, if false is returned, remove and destroy it */
            if (!onDataAvailable(c)) {
                /* Remove the client from our array */
                pthread_mutex_lock(&mClientsLock);
                for (it = mClients->begin(); it != mClients->end(); ++it) {
                    if (*it == c) {
                        mClients->erase(it);
                        break;
                    }
                }
                pthread_mutex_unlock(&mClientsLock);
                /* Destroy the client */
                int socket = c->getSocket();
                if (c->decRef()) {
                    // Note: 'c' is deleted memory at this point.
                    close(socket);
                }
            }
        }
    }
    delete pendingList;
}