void PGMConnection::close() { if( _state == STATE_CLOSED ) return; _printReadStatistics(); _printSendStatistics(); if( isListening( )) _exitAIOAccept(); else if( isConnected( )) _exitAIORead(); _state = STATE_CLOSED; EQASSERT( _readFD > 0 ); if( _readFD > 0 ) { const std::string& iName = _description->getInterface(); if( !iName.empty( )) { unsigned long interface; if( !_parseHostname( iName, interface ) || ::setsockopt( _readFD, IPPROTO_RM, RM_DEL_RECEIVE_IF, (char*)&interface, sizeof(uint32_t)) == SOCKET_ERROR ) { EQWARN << "can't delete recv interface " << base::sysError << std::endl; } } #ifdef _WIN32 const bool closed = ( ::closesocket( _readFD ) == 0 ); #else const bool closed = ( ::close( _readFD ) == 0 ); #endif if( !closed ) EQWARN << "Could not close read socket: " << base::sysError << std::endl; } if( _writeFD > 0 && isListening( )) { #ifdef _WIN32 const bool closed = ( ::closesocket( _writeFD ) == 0 ); #else const bool closed = ( ::close( _writeFD ) == 0 ); #endif if( !closed ) EQWARN << "Could not close write socket: " << base::sysError << std::endl; } _readFD = INVALID_SOCKET; _writeFD = INVALID_SOCKET; _fireStateChanged(); }
void QFrontDesk::setActive(bool active) { if(active && !isListening()) { if(listen(QHostAddress(ip_address), port)) { qDebug() << "QFrontDesk started on" << QString("http://%1:%2/").arg(ip_address, QString("%1").arg(port)); } else { qDebug() << "QFrontDesk: Error while starting server"; } return; } if(!active && isListening()) { close(); qDebug() << "QFrontDesk stopped"; return; } }
void TcpServer::close() { //TODO m_open = false; // wait until the server stops listening while (isListening()) { // spin until the server stops listening } printf("TcpServer: closing all ports\n"); if (::close(m_socket_number) < 0) { perror("TcpServer: close"); } std::map<int, ConnectionToClient*>::iterator it; for (it = m_clients.begin(); it != m_clients.end(); ++it) { if (::close(it->second->sock_fd) < 0) { perror("TcpServer: close"); } } serverClosed(); }
void SoftwareSerial::flush() { if (!isListening()) return; _receive_buffer_head = _receive_buffer_tail = 0; }
int SoftwareSerial::peek() { if (!isListening()) return -1; return _tty.peek(); }
void SoftwareSerial::flush() { if (!isListening()) return; _tty.flush(); }
int SoftwareSerial::available() { if (!isListening()) return 0; return _tty.available(); }
void CWebChannelServer::en_clientDisconnected(WebSocketTransport* pClient) { TWebChannelClientMap::iterator itrClientMap = m_mapChannels.find(pClient); assert(itrClientMap != m_mapChannels.end()); if (itrClientMap != m_mapChannels.end()) { QPointer<CWebChannelClient> pClientChannel = itrClientMap.value(); if (!pClientChannel.isNull()) delete pClientChannel; m_mapChannels.remove(pClient); #if DEBUG_WEBCHANNEL_SERVER_CONNECTIONS qDebug("Client Disconnection from: \"%s\" (%s) port %d -- %d Connections", pClient->socket()->peerName().toUtf8().data(), pClient->socket()->peerAddress().toString().toUtf8().data(), pClient->socket()->peerPort(), m_mapChannels.size()); #endif #ifdef IS_CONSOLE_APP std::cout << QString("%1 UTC : Disconnected : \"%2\" (%3) port %4 -- %5 Connections\n") .arg(QDateTime::currentDateTimeUtc().toString(Qt::ISODate)) .arg(pClient->socket()->peerName()) .arg(pClient->socket()->peerAddress().toString()) .arg(pClient->socket()->peerPort()) .arg(m_mapChannels.size()) .toUtf8().data(); std::cout.flush(); #endif } #ifdef IS_CONSOLE_APP if (m_mapChannels.isEmpty() && !isListening()) { // If the last client disconnects and the server was already made deaf, // then exit our daemon or else we'll have a stuck process: QCoreApplication::exit(0); } #endif }
eq::net::Connection::Notifier IBConnection::getNotifier() const { if( isListening( ) ) return _socketConnection->getNotifier(); return _readEvent; }
void Node::_connectMulticast( NodePtr node, ConnectionPtr connection ) { lunchbox::ScopedMutex<> mutex( _impl->outMulticast ); MCDatas::iterator i = node->_impl->multicasts.begin(); for( ; i != node->_impl->multicasts.end(); ++i ) { if( (*i).connection == connection ) break; } if( node->_impl->outMulticast->isValid( )) { if( node->_impl->outMulticast.data == connection ) { // nop, connection already used LBASSERT( i == node->_impl->multicasts.end( )); } else if( i == node->_impl->multicasts.end( )) { // another connection is used as multicast connection, save this LBASSERT( isListening( )); MCData data; data.connection = connection; data.node = this; _impl->multicasts.push_back( data ); } // else nop, already know connection } else { node->_impl->outMulticast.data = connection; if( i != node->_impl->multicasts.end( )) node->_impl->multicasts.erase( i ); } }
bool TThreadApplicationServer::start(bool debugMode) { if (isListening()) { return true; } bool res = loadLibraries(); if (!res) { if (debugMode) { tSystemError("Failed to load application libraries."); return false; } else { tSystemWarn("Failed to load application libraries."); } } if (listenSocket <= 0 || !setSocketDescriptor(listenSocket)) { tSystemError("Failed to set socket descriptor: %d", listenSocket); return false; } // instantiate if (!debugMode) { TSystemBus::instantiate(); TPublisher::instantiate(); } TUrlRoute::instantiate(); TSqlDatabasePool::instantiate(); TKvsDatabasePool::instantiate(); TStaticInitializeThread::exec(); return true; }
ConnectionPtr NamedPipeConnection::acceptSync() { LB_TS_THREAD( _recvThread ); if( !isListening( )) return 0; // complete accept DWORD got = 0; if( !GetOverlappedResult( _fd, &_read, &got, TRUE )) { if (GetLastError() == ERROR_PIPE_CONNECTED) { return 0; } LBWARN << "Accept completion failed: " << lunchbox::sysError << ", closing named pipe" << std::endl; close(); return 0; } lunchbox::RefPtr< NamedPipeConnection > newConnection = new NamedPipeConnection; newConnection->_setDescription( _getDescription( )); newConnection->_fd = _fd; newConnection->_initAIORead(); newConnection->_setState( STATE_CONNECTED ); _fd = INVALID_HANDLE_VALUE; LBINFO << "accepted connection" << std::endl; return newConnection; }
/*! Sets the socket descriptor this server should use when listening for incoming connections to \a socketDescriptor. Returns true if the socket is set successfully; otherwise returns false. The socket is assumed to be in listening state. \sa socketDescriptor(), isListening() */ bool QTcpServer::setSocketDescriptor(int socketDescriptor) { Q_D(QTcpServer); if (isListening()) { qWarning("QTcpServer::setSocketDescriptor() called when already listening"); return false; } if (d->socketEngine) delete d->socketEngine; d->socketEngine = QAbstractSocketEngine::createSocketEngine(socketDescriptor, this); if (!d->socketEngine->initialize(socketDescriptor, QAbstractSocket::ListeningState)) { d->serverSocketError = d->socketEngine->error(); d->serverSocketErrorString = d->socketEngine->errorString(); #if defined (QTCPSERVER_DEBUG) qDebug("QTcpServer::setSocketDescriptor(%i) failed (%s)", socketDescriptor, d->serverSocketErrorString.toLatin1().constData()); #endif return false; } d->socketEngine->setReceiver(d); d->socketEngine->setReadNotificationEnabled(true); d->state = d->socketEngine->state(); d->address = d->socketEngine->localAddress(); d->port = d->socketEngine->localPort(); #if defined (QTCPSERVER_DEBUG) qDebug("QTcpServer::setSocketDescriptor(%i) succeeded.", socketDescriptor); #endif return true; }
int SoftwareSerial::available() { if (!isListening()) return 0; return (_receive_buffer_tail + _SS_MAX_RX_BUFF - _receive_buffer_head) % _SS_MAX_RX_BUFF; }
/* returns: * 0 if succeed * 1 if length of the message>MAXMSGLEN * 2 for some other errors * TODO: return 0 only if OK was received */ byte SerialGSM::sendSMS(SMS& sms) { #ifdef DEBUG Serial.print(":: Sending SMS to :"); Serial.println(sms.phone_no); Serial.print(sms.message); Serial.println("<EOF>"); #endif println_d("AT+CMGF=1"); // set SMS mode to text delay(100); response = readline(buffer,BUFFERLEN,length_read); if(!isListening()) Serial.println(":: not listening!"); if(response<0) return 2; print_d("AT+CMGS=\""); print_d(sms.phone_no); println_d('"'); // ASCII equivalent of " delay(500); // give the module some thinking time response = readline(buffer,BUFFERLEN,length_read); if(response<0) return 2; println_d(sms.message); print_d(char(26)); // ASCII equivalent of Ctrl-Z delay(500); response = readline(buffer,BUFFERLEN,length_read); if(response<0) return 2; #ifdef DEBUG Serial.println(":: Message sending succeded."); #endif return 0; }
void SocketConnection::_close() { if( isClosed( )) return; if( isListening( )) _exitAIOAccept(); else if( isConnected( )) _exitAIORead(); LBASSERT( _readFD > 0 ); #ifdef _WIN32 const bool closed = ( ::closesocket(_readFD) == 0 ); #else const bool closed = ( ::close(_readFD) == 0 ); #endif if( !closed ) LBWARN << "Could not close socket: " << lunchbox::sysError << std::endl; _readFD = INVALID_SOCKET; _writeFD = INVALID_SOCKET; _setState( STATE_CLOSED ); }
int SoftwareSerial::read() { if (!isListening()) return -1; return _tty.read(); }
void EventDispatcher::fireIfExists(string event){ if(!isListening(event)){ return; } fire(event); }
int SoftwareSerial::available() { if (!isListening()) return 0; return (_receive_buffer_tail + _receive_buffer_size - _receive_buffer_head) % _receive_buffer_size; }
/*** int UdpServer::availableClients(void) ** ** Synopsis: ** Checks to see how many pending clients are availabe to be accepted. ** ** Parameters: ** None ** ** Return Values: ** The number of waiting UdpClients to be accepted. ** ** Errors: ** None ** ** Notes: ** ** This is the workhorse of the UdpServer Class ** It will update pending clients if a datagram is detected ** It will attempt to start listening if a socket comes avalialbe for listening ** It will clean up disconnected clients */ int UdpServer::availableClients(void) { int i = 0; EthernetPeriodicTasks(); if(isListening() && UdpClientAvailable(_rghUDP[_cPending]) > 0) { // remember, we listen on the last hUDP in the buffer. _cPending++; } // The AcceptClient could have removed someone from the list // do this first, so if we resume we have a socket to listen while(i <_cPending) { // see if we need to clear this one if(_rghUDP[i] >= INVALID_UDP_SOCKET) { int j = i; byte iBuff = _iBuff[i]; // this buffer came available // shift everyone from this location down. // include everything possible (_cPendingMax), even things beyond _cPending // because I want to shift the listening one at _rghUDP[_cPending] as well for(; j < _cPendingMax-1; j++) { _rghUDP[j] = _rghUDP[j+1]; _iBuff[j] = _iBuff[j+1]; } // we know the very last slot is open, because we just removed one and shifted down // make sure we have an invalid socket number in there. // also, since we shifted, the last 2 slots will have the same iBuff index // but we just opened up a new index that we just removed, move it to the last socket slot // we know this last socket slot is open, if we are not listening, then this will be picked // as our listening slot when we do the resume below _rghUDP[_cPendingMax-1] = INVALID_UDP_SOCKET; _iBuff[_cPendingMax-1] = iBuff; // reduce the pending count as we just removed one _cPending--; } // if nothing was shifted, look at the next value; if we shifted // don't increment as we want to look at he shifted one. else { i++; } } // if we are supposed to be listening, then try to listening if(_fListening) { resumeListening(); } return(_cPending); }
void NamedPipeConnection::_close() { if( isClosed( )) return; LBASSERT( _fd > 0 ); if( isListening( )) { _exitAIOAccept(); if( _fd != INVALID_HANDLE_VALUE && !DisconnectNamedPipe( _fd )) LBERROR << "Could not disconnect named pipe: " << lunchbox::sysError << std::endl; } else { _exitAIORead(); if( _fd != INVALID_HANDLE_VALUE && !CloseHandle( _fd )) LBERROR << "Could not close named pipe: " << lunchbox::sysError << std::endl; } _fd = INVALID_HANDLE_VALUE; _setState( STATE_CLOSED ); }
QString CWebChannelServer::url(const QString &strBaseURLGood, const QString &strBaseURLBad) const { QUrl aURL(m_server.isListening() ? strBaseURLGood : strBaseURLBad); if (isListening()) { aURL.setQuery(QStringLiteral("webChannelBaseUrl=") + m_server.serverUrl().toString()); } return aURL.toString(); }
bool EventDispatcher::hasPublisher(string event,IEventPublisher* publisher){ if(isListening(event)){ auto eventMap = listeners.at(event); return (eventMap.find(publisher) != eventMap.end())?true:false; } else { return false; } }
void CListenerSocket::RestartListening() { if(isListening()) { close(); } listen(QHostAddress::Any,CSettingsDialog::GetInstance()->GetPort()); }
void SoftwareSerial::flush() { if (!isListening()) return; io_DisableINT(); _receive_buffer_head = _receive_buffer_tail = 0; io_RestoreINT(); }
void SharedDaemon::init() { listen(QHostAddress::Any,listen_port); if(isListening()) std::cerr << "Starting to listen on port: " << listen_port << std::endl; else std::cerr << "WARNING: Failed to start listening server on port: " << listen_port << std::endl; }
ConnectionPtr SocketConnection::acceptSync() { LB_TS_THREAD( _recvThread ); if( !isListening( )) return 0; LBASSERT( _overlappedAcceptData ); LBASSERT( _overlappedSocket != INVALID_SOCKET ); if( _overlappedSocket == INVALID_SOCKET ) return 0; // complete accept DWORD got = 0; DWORD flags = 0; if( !WSAGetOverlappedResult( _readFD, &_overlappedRead, &got, TRUE, &flags )) { LBWARN << "Accept completion failed: " << lunchbox::sysError << ", closing socket" << std::endl; close(); return 0; } sockaddr_in* local = 0; sockaddr_in* remote = 0; int localLen = 0; int remoteLen = 0; GetAcceptExSockaddrs( _overlappedAcceptData, 0, sizeof( sockaddr_in ) + 16, sizeof( sockaddr_in ) + 16, (sockaddr**)&local, &localLen, (sockaddr**)&remote, &remoteLen ); _tuneSocket( _overlappedSocket ); ConstConnectionDescriptionPtr description = getDescription(); SocketConnection* newConnection = new SocketConnection; ConnectionPtr connection( newConnection ); // to keep ref-counting correct newConnection->_readFD = _overlappedSocket; newConnection->_writeFD = _overlappedSocket; #ifndef _WIN32 //fcntl( _overlappedSocket, F_SETFL, O_NONBLOCK ); #endif newConnection->_initAIORead(); _overlappedSocket = INVALID_SOCKET; newConnection->_setState( STATE_CONNECTED ); ConnectionDescriptionPtr newDescription = newConnection->_getDescription(); newDescription->bandwidth = description->bandwidth; newDescription->port = ntohs( remote->sin_port ); newDescription->setHostname( getHostName( *remote )); LBDEBUG << "accepted connection from " << newDescription->getHostname() << ":" << newDescription->port << std::endl; return connection; }
void MyServer::startServer(){ qDebug("Start server"); if (isListening()){ qDebug()<<"close server"; close(); } loadFile(); printDictionary(dictionary); if (!listen(QHostAddress::Any, nPort)){ qDebug()<<"Unable to start Server:"<<errorString(); close(); return; } connect(this, SIGNAL(newConnection()),this,SLOT(slotNewConnection())); qDebug() << isListening() << "TCPSocket listen on port" << nPort; }
bool TApplicationServer::open() { T_TRACEFUNC(); if (!isListening()) { quint16 port = Tf::app()->treefrogSettings().value("ListenPort").toUInt(); if (!nativeListen(QHostAddress::Any, port)) { tSystemError("listen failed. port:%d", port); return false; } else { tSystemDebug("listen successfully. port:%d", port); } } // Loads libraries if (!libLoaded) { // Sets work directory QString libPath = Tf::app()->libPath(); if (QDir(libPath).exists()) { // To resolve the symbols in the app libraries QDir::setCurrent(libPath); } else { tSystemError("lib directory not found"); return false; } QStringList filter; #if defined(Q_OS_WIN) filter << "controller.dll" << "view.dll"; #elif defined(Q_OS_DARWIN) filter << "libcontroller.dylib" << "libview.dylib"; #elif defined(Q_OS_UNIX) filter << "libcontroller.so" << "libview.so"; #else filter << "libcontroller.*" << "libview.*"; #endif QDir controllerDir("."); QStringList list = controllerDir.entryList(filter, QDir::Files); for (QStringListIterator i(list); i.hasNext(); ) { QString path = controllerDir.absoluteFilePath(i.next()); QLibrary lib(path); if (lib.load()) { tSystemDebug("Library loaded: %s", qPrintable(path)); libLoaded = true; } else { tSystemDebug("%s", qPrintable(lib.errorString())); } } } TUrlRoute::initialize(); TSqlDatabasePool::initialize(); return true; }
bool LocalServer::start() { while (!isListening() && !listen(QHostAddress::LocalHost, PORT)) { uERROR << "cannot start listening"; return false; } uINFO << "listening on port" << serverPort(); return true; }