void NNTPConnector::getResponseStream(std::ostream &out, int const count, std::string const &escapeSequence) { readFromSocket(out, count, escapeSequence); }
int communication::serverListen(int portNum,messageQueue<Packet*> *queue){ int servSock; int clntSock; Packet msg; struct sockaddr_in echoServAddr; struct sockaddr_in echoClntAddr; unsigned short echoServPort; socklen_t clntLen; echoServPort = portNum; if((servSock = socket(PF_INET,SOCK_STREAM,IPPROTO_TCP)) < 0) errorAndTerminate("Socket() failed\n"); memset(&echoServAddr,0,sizeof(echoServAddr)); echoServAddr.sin_family = AF_INET; echoServAddr.sin_addr.s_addr = htonl(INADDR_ANY); echoServAddr.sin_port = htons(echoServPort); if(bind(servSock,(struct sockaddr*)&echoServAddr,sizeof(echoServAddr)) < 0) errorAndTerminate("bind() failed\n"); if(listen(servSock,MAXPENDING) < 0 ) errorAndTerminate("listen() failed\n"); clntLen = sizeof(echoClntAddr); if((clntSock = accept(servSock,(struct sockaddr*)&echoClntAddr,&clntLen)) < 0) errorAndTerminate("accept() failed\n"); char *client_ip = inet_ntoa(echoClntAddr.sin_addr); readFromSocket(clntSock,&msg,sizeof(msg)); cout<<"Received msg from IP:"<<client_ip<<endl; queue->add(&msg); close(servSock); //@@ }
/* * Admin commands */ void MPDDatabaseConnection::update() { QByteArray *data; sendCommand("update"); data = readFromSocket(); delete data; }
void LocalJsonServer::clientReadyRead() { QLocalSocket* socket = dynamic_cast<QLocalSocket*>(sender()); if (!socket) return; QVariantList messages = readFromSocket(socket); foreach (const QVariant& msg, messages) emit messageReceived(msg.toMap()); }
void MPDPlaylistsConnection::listPlaylist() { QByteArray *data; sendCommand("listplaylist"); data = readFromSocket(); delete data; disconnectFromMPD(); }
/** * Get all the files and dir in the mpdmusic dir. * */ void MPDDatabaseConnection::listAll() { QByteArray *data; sendCommand("listall"); data = readFromSocket(); emit dirViewUpdated(MPDParseUtils::parseDirViewItems(data)); delete data; }
/** * Get all files in the playlist with detailed info (artist, album, * title, time etc). * * @param db_update The last update time of the library */ void MPDDatabaseConnection::listAllInfo(QDateTime db_update) { QByteArray *data; sendCommand("listallinfo"); data = readFromSocket(); emit musicLibraryUpdated(MPDParseUtils::parseLibraryItems(data), db_update); delete data; }
Manager::Manager(QObject *_parent) : QObject(_parent) , m_tcpSocket(new QTcpSocket(this)) , m_status(tr("Disconnected")) , m_currentCommand(MaxCommand) { connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(readFromSocket())); connect(m_tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(disconnected())); }
/** * list info from a direction * * TODO: db_update should be parsed correctly */ void MPDDatabaseConnection::lsInfo() { QByteArray *data; sendCommand("lsinfo"); data = readFromSocket(); emit musicLibraryUpdated(MPDParseUtils::parseLibraryItems(data), QDateTime()); delete data; }
void MPDPlaylistsConnection::listPlaylists() { QByteArray *data; sendCommand("listplaylists"); data = readFromSocket(); emit playlistsRetrieved(MPDParseUtils::parsePlaylists(data)); delete data; disconnectFromMPD(); }
void TinyWebServer::onNewConnection() { Q_ASSERT( m_tcpServer ); m_clientSocket = m_tcpServer->nextPendingConnection(); if ( m_clientSocket ) { connect( m_clientSocket, SIGNAL( disconnected() ), m_clientSocket, SLOT( deleteLater() ) ); connect( m_clientSocket, SIGNAL( readyRead() ), SLOT( readFromSocket() ) ); } }
void MaiaXmlRpcServerConnection::run() { connect(_clientConnection, SIGNAL(readyRead()), this, SLOT(readFromSocket())); connect(_clientConnection, SIGNAL(disconnected()), this, SLOT(quit())); _keepAlive = false; _keepAliveTimer.setInterval(_connectionTimeOut*1000); _keepAliveTimer.setSingleShot(true); connect(&_keepAliveTimer, SIGNAL(timeout()), this, SLOT(closeConnection())); exec(); }
void loop() { for(int i = 0; i < getCanBusCount(); i++) { receiveCan(&getCanBuses()[i]); } readFromHost(listener.usb, receiveWriteRequest); readFromSerial(listener.serial, receiveWriteRequest); readFromSocket(listener.ethernet, receiveWriteRequest); for(int i = 0; i < getCanBusCount(); i++) { processCanWriteQueue(&getCanBuses()[i]); } updateDataLights(); }
void TMsgCore::OnReadyRead() // server side { std::set<QTcpSocket *>::iterator it = m_sockets.begin(); for (; it != m_sockets.end(); it++) // devo scorrerli tutti perche' non so da // quale socket viene il messaggio... { if ((*it)->state() == QTcpSocket::ConnectedState && (*it)->bytesAvailable() > 0) break; } if (it != m_sockets.end()) { readFromSocket(*it); OnReadyRead(); } }
CString DLRacerInterface::sendCommand(CString strCommand) { strCommand += _T("\n"); int status; status = send(racerSocket, strCommand, strCommand.GetLength(), 0); if (status == -1) { int dwError = WSAGetLastError(); MyMessageBox_Error(_T("sendCommand")); return _T("null"); } CString strResult = readFromSocket(); return parseResult(strCommand, strResult); }
bool SocketConnection::read( SocketConnector& s ) { if ( !m_pSession ) return false; try { readFromSocket(); readMessages( s.getMonitor() ); } catch( SocketRecvFailed& e ) { m_pSession->getLog()->onEvent( e.what() ); return false; } return true; }
std::string NNTPConnector::getResponseString(int const count, std::string const &escapeSequence, bool const doEmit) { std::ostringstream ss; readFromSocket(ss, count, escapeSequence); std::string response = ss.str(); if(doEmit) { std::stringstream ss(response); std::string statusLine; std::getline(ss,statusLine); emit statusSignal(QString(statusLine.c_str())); } return response; }
void DefaultOperationTcpChannel::onReadEvent(const boost::system::error_code& err) { if (!err) { std::ostringstream responseStream; responseStream << responseBuffer_.get(); const auto& responseStr = responseStream.str(); try { if (responseStr.empty()) { KAA_LOG_ERROR(boost::format("Channel [%1%] no data read from socket") % getId()); } else { responseProcessor.processResponseBuffer(responseStr.data(), responseStr.size()); } } catch (const TransportRedirectException& exception) { KAA_LOG_INFO(boost::format("Channel [%1%] received REDIRECT response") % getId()); return; } catch (const KaaException& exception) { KAA_LOG_ERROR(boost::format("Channel [%1%] failed to process data: %2%") % getId() % exception.what()); onServerFailed(); } } else { KAA_LOG_WARN(boost::format("Channel [%1%] socket error: %2%") % getId() % err.message()); KAA_MUTEX_LOCKING("channelGuard_"); KAA_MUTEX_UNIQUE_DECLARE(channelLock, channelGuard_); KAA_MUTEX_LOCKED("channelGuard_"); if (err != boost::asio::error::operation_aborted && isConnected_) { KAA_MUTEX_UNLOCKING("channelGuard_"); KAA_UNLOCK(channelLock); KAA_MUTEX_UNLOCKED("channelGuard_") onServerFailed(); return; } else { KAA_LOG_DEBUG(boost::format("Channel [%1%] socket operations aborted") % getId()); return; } } KAA_MUTEX_LOCKING("channelGuard_"); KAA_MUTEX_UNIQUE_DECLARE(channelLock, channelGuard_); KAA_MUTEX_LOCKED("channelGuard_"); if (isConnected_) { readFromSocket(); } }
ServiceClient::ServiceClient(QObject *parent) : QObject(parent) { m_qTcpSocket = new QTcpSocket(this); connect(m_qTcpSocket, SIGNAL(connected()), this, SLOT(sltConnected())); connect(m_qTcpSocket, SIGNAL(disconnected()), this, SLOT(sltDisconnected())); connect(m_qTcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(reportError(QAbstractSocket::SocketError)), Qt::DirectConnection); connect(m_qTcpSocket, SIGNAL(readyRead()), this, SLOT(readFromSocket()), Qt::DirectConnection); #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN m_bIsLittleEndian = true; #endif #if Q_BYTE_ORDER == Q_BIG_ENDIAN m_bIsLittleEndian = false; #endif }
bool SocketConnection::read( SocketAcceptor& a, SocketServer& s ) { std::string msg; try { if ( !m_pSession ) { struct timeval timeout = { 1, 0 }; fd_set readset = m_fds; while( !readMessage( msg ) ) { int result = select( 1 + m_socket, &readset, 0, 0, &timeout ); if( result > 0 ) readFromSocket(); else if( result == 0 ) return false; else if( result < 0 ) return false; } m_pSession = Session::lookupSession( msg, true ); if( !isValidSession() ) { m_pSession = 0; if( a.getLog() ) { a.getLog()->onEvent( "Session not found for incoming message: " + msg ); a.getLog()->onIncoming( msg ); } } if( m_pSession ) m_pSession = a.getSession( msg, *this ); if( m_pSession ) m_pSession->next( msg, UtcTimeStamp() ); if( !m_pSession ) { s.getMonitor().drop( m_socket ); return false; } Session::registerSession( m_pSession->getSessionID() ); return true; } else { readFromSocket(); readMessages( s.getMonitor() ); return true; } } catch ( SocketRecvFailed& e ) { if( m_pSession ) m_pSession->getLog()->onEvent( e.what() ); s.getMonitor().drop( m_socket ); } catch ( InvalidMessage& ) { s.getMonitor().drop( m_socket ); } return false; }
void DefaultOperationTcpChannel::openConnection() { if (isConnected_) { KAA_LOG_WARN(boost::format("Channel [%1%] connection is already opened") % getId()); return; } KAA_LOG_TRACE(boost::format("Channel [%1%] opening connection to %2%:%3%") % getId() % currentServer_->getHost() % currentServer_->getPort()); boost::system::error_code errorCode; boost::asio::ip::tcp::endpoint ep = HttpUtils::resolveEndpoint(currentServer_->getHost(), currentServer_->getPort(), errorCode); if (errorCode) { KAA_LOG_ERROR(boost::format("Channel [%1%] failed to resolve endpoint: %2%") % getId() % errorCode.message()); onServerFailed(); return; } responseBuffer_.reset(new boost::asio::streambuf()); sock_.reset(new boost::asio::ip::tcp::socket(io_)); sock_->open(ep.protocol(), errorCode); if (errorCode) { KAA_LOG_ERROR(boost::format("Channel [%1%] failed to open socket: %2%") % getId() % errorCode.message()); onServerFailed(); return; } sock_->connect(ep, errorCode); if (errorCode) { KAA_LOG_ERROR(boost::format("Channel [%1%] failed to connect to %2%:%3%: %4%") % getId() % ep.address().to_string() % ep.port() % errorCode.message()); onServerFailed(); return; } channelManager_.onConnected({sock_->local_endpoint().address().to_string(), ep.address().to_string(), getServerType()}); KAA_MUTEX_LOCKING("channelGuard_"); KAA_LOCK(channelGuard_); KAA_MUTEX_LOCKED("channelGuard_"); isConnected_ = true; KAA_MUTEX_UNLOCKING("channelGuard_"); KAA_UNLOCK(channelGuard_); KAA_MUTEX_UNLOCKED("channelGuard_"); sendConnect(); setConnAckTimer(); readFromSocket(); setPingTimer(); }
int main(int argc, char** argv) { int count = 0; char msgBuf[MAX_MSG_LEN]; // Process command line arguments if (argc < MIN_ARG_COUNT) { printf("Not enough arguments provided.\n"); return INSUFFICIENT_ARGS; } memset( msgBuf, 0, MAX_MSG_LEN); // Create a local socket SOCK serverSock = socket(AF_LOCAL, SOCK_STREAM, 0); if (serverSock < 0) { printf("Failed to create a socket: %s\n", strerror(errno)); return SOCK_CREATE_FAIL; } // Bind the created socket struct sockaddr_un sockAddr; sockAddr.sun_family = AF_UNIX; strncpy(sockAddr.sun_path, argv[SOCK_FILE_ARG_IDX], UNIX_PATH_MAX); if (bind(serverSock, (struct sockaddr*) &sockAddr, sizeof(sockAddr)) < 0) { printf("Failed to bind the socket: %s\n", strerror(errno)); return BIND_FAIL; } // Listen on the bound socket if (listen(serverSock, BACKLOG_SIZE) < 0) { printf("Failed to listen on the bound socket: %s\n", strerror(errno)); return LISTEN_FAIL; } while( 1 ) { printf( "Waiting for connection...\n" ); // Accept a single connection struct sockaddr_un clientAddr; clientAddr.sun_family = AF_UNIX; SOCK clientSock = accept(serverSock, NULL, NULL); if (clientSock < 0) { printf("Failed to accept a client connection: %s\n", strerror(errno)); return ACCEPT_FAIL; } printf( "Client Connected: %d\n", clientSock ); memset( msgBuf, 0, MAX_MSG_LEN); while( strncmp( msgBuf, "quit", MAX_MSG_LEN ) != 0 ) { int res = readFromSocket(clientSock, msgBuf); if( res < 0 ) { printf( "ERROR: Recieving error %s\n", strerror(errno)); break; } else if( res > 0 ) { printf("%s\n", msgBuf); } } close( clientSock ); } // Close the connections close(serverSock); if (unlink(argv[SOCK_FILE_ARG_IDX]) < 0) { printf("Failed when disposing of system resources: %s\n", strerror(errno)); return UNLINK_FAIL; } return SUCCESS; }
// -------------------------------------------------------------------- // processPacket // -------------------------------------------------------------------- bool processPacket(int sock, File* outFile, bool display, bool &close) { LogPacketHeader packetHeader((LogType)0); struct tm *timeInfo=NULL; bool magicOK = false; int magic=0; static Byte data[LOG_DATA_MAX_LENGTH]; close=false; // look for magic while (!magicOK) { Byte byte=0; while(1) { if (peekFromSocket(sock, &byte, 1)==0) { if (byte==0xa0) break; else readFromSocket(sock, &byte, 1); } } if (peekFromSocket(sock, &magic, sizeof(int))==0) { if (magic != LOG_MAGIC_NBR) { printf ("*** Packet corrupted try to resynchronize (magic " ": 0x%x != 0x%x) !!!\n", magic, LOG_MAGIC_NBR); readFromSocket(sock, &magic, sizeof(int)); } else { break; } } else { return false; } } if (readFromSocket(sock, &packetHeader, sizeof(LogPacketHeader))==0) { if (display) { printf(" timeStamp = "); timeInfo = localtime(&packetHeader.timeStamp.tv_sec); printf("%02d/%02d/%02d %02d:%02d:%02d,%06d\n", timeInfo->tm_mday, timeInfo->tm_mon+1, timeInfo->tm_year+1900, timeInfo->tm_hour, timeInfo->tm_min, timeInfo->tm_sec, (int)packetHeader.timeStamp.tv_usec); } if (packetHeader.type == LOG_TYPE_CLOSE) { printf("Closing log\n"); close=true; return false; } //printf("read length=%d\n", packetHeader.length); if (readFromSocket(sock, data, packetHeader.length)==0) { if (display) { displayPacket(packetHeader, data); } } storePacket(outFile, packetHeader, data); return true; } else { printf("read error\n"); return false; } }
MaiaXmlRpcServerConnection::MaiaXmlRpcServerConnection(QTcpSocket *connection, QObject* parent) : QObject(parent) { header = NULL; clientConnection = connection; connect(clientConnection, SIGNAL(readyRead()), this, SLOT(readFromSocket())); connect(clientConnection, SIGNAL(disconnected()), this, SLOT(deleteLater())); }
void mdtTcpSocketThread::run() { Q_ASSERT(pvPort != 0); mdtTcpSocket *socket; pvPort->lockMutex(); // Init write frame pvWriteCurrentFrame = 0; // Get a RX frame pvReadCurrentFrame = getNewFrameRead(); if(pvReadCurrentFrame == 0){ mdtError e(MDT_TCP_IO_ERROR, "No frame available in read frames pool, stopping thread", mdtError::Error); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); pvRunning = false; pvPort->unlockMutex(); return; } // Alloc the local buffer pvReadBufferSize = pvReadCurrentFrame->capacity(); pvReadBuffer = new char[pvReadBufferSize]; if(pvReadBuffer == 0){ mdtError e(MDT_TCP_IO_ERROR, "Cannot allocate memory for local read buffer" , mdtError::Error); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); pvRunning = false; pvReadBufferSize = 0; pvPort->unlockMutex(); return; } //bufferCursor = buffer; // Create a Tcp socket pvSocket = new QTcpSocket; Q_ASSERT(pvSocket != 0); // We must pass this socket object to pvPort // pvPort must be a instance of mdtTcpSocket socket = dynamic_cast<mdtTcpSocket*>(pvPort); Q_ASSERT(socket != 0); socket->setThreadObjects(pvSocket, this); // Set the running flag pvRunning = true; // Run... while(1){ // Read thread state if(!pvRunning){ break; } // Check if a connection was requested if(pvPeerPort == 0){ socket->waitForNewTransaction(); } if(pvSocket->state() == QAbstractSocket::ConnectedState){ // Wait on write ready event if(!pvPort->waitEventWriteReady()){ emit(errorOccured(MDT_TCP_IO_ERROR)); /// NOTE: sleep ? } // Read thread state if(!pvRunning){ break; } // ********************** // Event occured, send the data to port - Check timeout state first if(!pvPort->writeTimeoutOccured()){ // Write data to send writeToSocket(); } // Wait until data is available for read if(!pvPort->waitForReadyRead()){ emit(errorOccured(MDT_TCP_IO_ERROR)); /// NOTE: sleep ? } // Read thread state if(!pvRunning){ break; } // ********************** // Event occured, get the data from port - Check timeout state first if(!pvPort->readTimeoutOccured()){ // We received data , read it readFromSocket(); } }else{ // Try to (Re-)connect if(!reconnectToHost()){ qDebug() << "TCP THD: SIGNAL: Cannot reconnect - Retry at next transaction ..."; socket->waitForNewTransaction(); } } } // Put current frame into pool if(pvReadCurrentFrame != 0){ pvPort->readFramesPool().enqueue(pvReadCurrentFrame); } // End connection if(pvSocket->state() == QAbstractSocket::ConnectedState){ pvSocket->disconnectFromHost(); if(pvSocket->state() != QAbstractSocket::UnconnectedState){ // Wait on disconnected if(!pvSocket->waitForDisconnected(500)){ mdtError e(MDT_TCP_IO_ERROR, "Cannot wait for disconnected" , mdtError::Error); e.setSystemError(pvSocket->error(), pvSocket->errorString()); MDT_ERROR_SET_SRC(e, "mdtTcpSocketThread"); e.commit(); } } } // Free memory Q_ASSERT(pvReadBuffer != 0); delete pvReadBuffer; pvPort->unlockMutex(); }
int StreamingAudioClient::start(int x, int y, int width, int height, int depth, unsigned int timeout) { if (m_port >= 0) return SAC_ERROR; // already registered if (!m_samIP) return SAC_ERROR; // not initialized yet printf("\n"); printf("--------------------------------------\n"); printf("Streaming Audio Client version %d.%d.%d\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); printf("Built on %s at %s\n", __DATE__, __TIME__); printf("Copyright UCSD 2011-2013\n"); printf("Connecting to SAM at IP %s, port %d\n", m_samIP, m_samPort); printf("--------------------------------------\n\n"); // bind to local IP and port (Qt 5+ only) if (m_replyIP || m_replyPort > 0) { #if QT_VERSION >= 0x050000 if (m_replyIP) { QString replyIPStr(m_replyIP); QHostAddress replyIPAddr(replyIPStr); m_socket.bind(replyIPAddr, m_replyPort); } else { m_socket.bind(QHostAddress::Any, m_replyPort); } #else qWarning("Couldn't bind to specified local IP and port. Qt version 5.0+ required."); return SAC_ERROR; #endif } QString samIPStr(m_samIP); m_socket.connectToHost(samIPStr, m_samPort); if (!m_socket.waitForConnected(timeout)) { qWarning("StreamingAudioClient::start() couldn't connect to SAM"); return SAC_TIMEOUT; } m_replyPort = m_socket.localPort(); // set up listening for OSC messages m_oscReader = new OscTcpSocketReader(&m_socket); connect(&m_socket, SIGNAL(readyRead()), m_oscReader, SLOT(readFromSocket())); connect(m_oscReader, SIGNAL(messageReady(OscMessage*, const char*, QAbstractSocket*)), this, SLOT(handleOscMessage(OscMessage*, const char*, QAbstractSocket*))); connect(&m_socket, SIGNAL(disconnected()), this, SLOT(samDisconnected())); OscMessage msg; msg.init("/sam/app/register", "siiiiiiiiiiiiii", m_name, m_channels, x, y, width, height, depth, m_type, m_preset, 0, // placeholder for packet size/samples per packet requested m_packetQueueSize, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, m_replyPort); if (!OscClient::sendFromSocket(&msg, &m_socket)) { qWarning("StreamingAudioClient::start() Couldn't send OSC message"); return SAC_OSC_ERROR; } // wait on response from SAM QEventLoop loop; connect(this, SIGNAL(responseReceived()), &loop, SLOT(quit())); QTimer::singleShot(timeout, &loop, SLOT(quit())); loop.exec(); if (!m_responseReceived) { qWarning("StreamingAudioClient::start() timed out waiting for response to register request"); return SAC_TIMEOUT; } else if (m_port < 0) { return SAC_REQUEST_DENIED; } return SAC_SUCCESS; }
bool SocketConnection::read( SocketAcceptor& a, SocketServer& s ) { std::string msg; try { if ( !m_pSession ) { int timeout = 1000; // 1000ms = 1 second struct pollfd pfd = { m_socket, POLLIN | POLLPRI, 0 }; while( !readMessage( msg ) ) { int result = poll( &pfd, 1, timeout ); if( result > 0 ) readFromSocket(); else if( result == 0 ) return false; else if( result < 0 ) return false; } m_pSession = Session::lookupSession( msg, true ); if( !isValidSession() ) { m_pSession = 0; if( a.getLog() ) { a.getLog()->onEvent( "Session not found for incoming message: " + msg ); a.getLog()->onIncoming( msg ); } } if( m_pSession ) m_pSession = a.getSession( msg, *this ); if( m_pSession ) m_pSession->next( msg, UtcTimeStamp() ); if( !m_pSession ) { s.getMonitor().drop( m_socket ); return false; } Session::registerSession( m_pSession->getSessionID() ); return true; } else { readFromSocket(); readMessages( s.getMonitor() ); return true; } } catch ( SocketRecvFailed& e ) { if( m_pSession ) m_pSession->getLog()->onEvent( e.what() ); s.getMonitor().drop( m_socket ); } catch ( InvalidMessage& ) { s.getMonitor().drop( m_socket ); } return false; }