CSocketListener::CSocketListener(int port) { //Creat mListenerSocket mListenerSocket.create(CSocket::C_SOCKET_NETWORK); mListenerSocket.bind(nullptr, port); mListenerSocket.setBlocking(false); //Stop main thread or not //default value is false mShouldStop = false; }
while(!mShouldStop) { /*When the listener fd is readable, it indicates that there is a new connection*/ if (mSelectFds.select(CSelect::C_FDS_READ| CSelect::C_FDS_ERROR) <= 0) { printf("ms_socket_listener select error, errno = %d.", errno); CThread::sleep(1000); continue; }
if (mSelectFds.isSetFd(CSelect::C_FDS_READ, mListenerSocket.getSocketFd())) { socket_fd = mListenerSocket.accept();
mSelectFds.addFd(CSelect::C_FDS_READ| CSelect::C_FDS_ERROR, socket_fd); mMutex.lock(); mClientLists.push_back(client); mMutex.unlock(); } } /*Whether all clients in client lists is readable or not*/ mMutex.lock(); for (it = mClientLists.begin(); it != mClientLists.end();) { socket_fd = (*it)->getSocket()->getSocketFd();
/*Send to all clients*/ voidCSocketListener::sendBroadcast(char *data, int length) { std::list<std::shared_ptr<CSocketClient >>::iterator it; mMutex.lock(); for (it = mClientLists.begin(); it != mClientLists.end(); it++) { if ((*it)->sendData(data, length) < 0) { /*error*/ } } mMutex.unlock(); }
/*Send to the specified client*/ intCSocketListener::sendClient(std::shared_ptr<CSocketClient > client, char *data, int length) { int ret = -1; std::list<std::shared_ptr<CSocketClient >>::iterator it; mMutex.lock(); for (it = mClientLists.begin(); it != mClientLists.end(); it++) { if ((*it).get() == client.get()) { ret = (*it)->sendData(data, length); if ( ret < 0) { /*error*/ } break; } } mMutex.unlock(); return ret; }