void brain_stroke_server::deal_next_request(){
    puts("deal next");
    //get next request
    deque_mutex.lock();
    if(request_list.size() != 0){
        puts("has next");
        QTcpSocket * client = request_list.front();
        request_list.pop_front();
        deque_mutex.unlock();
        //ignore closing socket
        if(client->state() == QTcpSocket::UnconnectedState || client->state() == QTcpSocket::ClosingState){
            client->close();
            QLOG_DEBUG() << "close client" << client;
            std::cout << "close client:" << client->peerAddress().toString().toStdString() << std::endl;
            //search next from request_list
            deal_next_request();
            return;
        }
        tcp_deal * tcp_deal_thread = new tcp_deal();
        tcp_deal_thread -> set_socket(client);
        connect(tcp_deal_thread, SIGNAL(finished()), this, SLOT(deal_next_request()));
        connect(tcp_deal_thread, SIGNAL(finished()), tcp_deal_thread, SLOT(deleteLater()));
        tcp_deal_thread -> start();
        return;
    }
    deque_mutex.unlock();
    QMutexLocker calculate_flag_mutex_locker(&calculate_flag_mutex);
    //no calculating now
    calculate_flag = false;
    return;
}
Exemple #2
0
bool Server::SendData(QHostAddress ip_to, QString message)
{
    bool result = false;
    QTcpSocket* tcpSocket = sockets->value(ip_to.toIPv4Address(), 0);
    if (tcpSocket && tcpSocket->state()==QAbstractSocket::ConnectedState && tcpSocket->isWritable()) {
        emit write_message(tr("Sending data (size=%1) to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
        tcpSocket->write(message.toUtf8());
        result = tcpSocket->waitForBytesWritten();
    } else {
        tcpSocket = new QTcpSocket();
        tcpSocket->connectToHost(ip_to, remote_port, QIODevice::ReadWrite);
        tcpSocket->waitForConnected(5000);

        if (tcpSocket->state()==QAbstractSocket::ConnectedState) {
            emit write_message(tr("Sending data (size=%1) from new socket to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message));
            tcpSocket->write(message.toUtf8());
            result = tcpSocket->waitForBytesWritten(5000);
        } else {
            emit error(tr("Client \"%1\" not found").arg(ip_to.toString()));
        }

        tcpSocket->abort();
        delete tcpSocket;
    }
    return result;
}
Exemple #3
0
void streamLoop(qintptr socketDesc, QQueue<QByteArray> &queue, bool& streaming) {

    QTcpSocket* socket = new QTcpSocket();
    // TCP_NODELAY + disable Nagle's algorithm
    socket->setSocketOption(QAbstractSocket::LowDelayOption, QVariant::fromValue(1));
    // Internetwork control
    socket->setSocketOption(QAbstractSocket::TypeOfServiceOption, QVariant::fromValue(192));
    socket->setSocketDescriptor(socketDesc);
    socket->readAll();

    QByteArray ContentType = ("HTTP/1.1 200 OK\r\n" \
                              "Server: test\r\n" \
                              "Cache-Control: no-cache\r\n" \
                              "Cache-Control: private\r\n" \
                              "Connection: close\r\n"\
                              "Pragma: no-cache\r\n"\
                              "Content-Type: multipart/x-mixed-replace; boundary=--boundary\r\n\r\n");

    socket->write(ContentType);

    while((socket->state() != QAbstractSocket::ClosingState ||
           socket->state() != QAbstractSocket::UnconnectedState) &&
           socket->state() == QAbstractSocket::ConnectedState &&
           streaming) {

        if(queue.empty()) { // no new frame available
            continue;
        }

        // make sure that the queue doesn't grow too big or
        // the OOM killer will kick in
        if(queue.length() > 20) {
            queue.clear();
            continue;
        }

        QByteArray boundary = ("--boundary\r\n" \
                               "Content-Type: image/jpeg\r\n" \
                               "Content-Length: ");

        QByteArray img  = queue.dequeue();
        boundary.append(QString::number(img.length()));
        boundary.append("\r\n\r\n");

        socket->write(boundary);
        socket->waitForBytesWritten();
        boundary.clear();
        socket->write(img);
        socket->waitForBytesWritten();
        img.clear();
    }

    socket->flush();
    socket->abort();
    socket->deleteLater();
    streaming = false;
    queue.clear();
    return;
}
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata)
{
    /// Send appropriate message for TCP or WebConnection
    void** data = (void**)cbdata;
    ConnectionType typeOfConnection = *((ConnectionType*)(data[0]));
    QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]);
    ViewerState* viewerState = static_cast<ViewerState*>(data[2]);

    JSONNode node;

    QString hostname = typeOfConnection == TcpConnection ? socket->localAddress().toString():
                        dynamic_cast<QWsSocket*>(socket)->internalSocket()->localAddress().toString();

    if(hostMap.contains(hostname)) hostname = hostMap[hostname];

    node["host"] = hostname.toStdString(); //host
    node["port"]  = args[7]; //port
    node["version"] = args[2]; //version
    node["securityKey"] = args[9]; //key
    node["numStates"] = viewerState->GetNumStateObjects(); //number of states

    JSONNode::JSONArray rpc_array = JSONNode::JSONArray();

    for(size_t i = 0; i < ViewerRPC::MaxRPC; ++i) {
        rpc_array.push_back(ViewerRPC::ViewerRPCType_ToString((ViewerRPC::ViewerRPCType)i));
    }
    node["rpc_array"] = rpc_array;

    if(typeOfConnection == TcpConnection)
    {
        QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket);

        std::string message = node.ToString();
        tsocket->write(message.c_str(),message.length());

        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForBytesWritten();
        tsocket->disconnectFromHost();
        if(tsocket->state() != QAbstractSocket::UnconnectedState)
            tsocket->waitForDisconnected();
        //HKTODO: Do not delete connection (test fix for ORNL machines)
        //tsocket->deleteLater();
    }
    else
    {
        QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket);

        wsocket->write(QString(node.ToString().c_str()));
        wsocket->flush();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForBytesWritten();

        wsocket->close("");
        wsocket->internalSocket()->disconnectFromHost();
        if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState)
            wsocket->internalSocket()->waitForDisconnected();
        wsocket->deleteLater();
    }
}
Exemple #5
0
void TcpEchoServerSession::run()
{
    LOG_INFO("Beginning of TcpEchoServerSession::run");

    QTcpSocket socket;
    if( !socket.setSocketDescriptor(m_socketDescriptor))
    {
        LOG_ERROR("Cannot set socket descriptor");
    }

    while( true )
    {
        // Receive request
        qint16 fillSize;
        qint16 echoSize;

        while( socket.bytesAvailable() < 4 )
        {
            if( !socket.waitForReadyRead(-1)) // Intervals may vary
            {
                break;
            }
        }
        if( socket.state() == QAbstractSocket::UnconnectedState )
        {
            break; // Connection closed by client
        }

        QDataStream in(&socket);
        in >> fillSize >> echoSize;
        
        // Receive filled bytes in the request
        while( socket.bytesAvailable() < fillSize )
        {
            if( !socket.waitForReadyRead(3 * 1000))
            {
                LOG_INFO("TcpEcho session timed out");
                return;
            }
        }
        socket.read(fillSize);
        
        // Send data
        QByteArray block(echoSize, 0);
        socket.write(block);
        socket.waitForBytesWritten(-1);

        if( socket.state() == QAbstractSocket::UnconnectedState )
        {
            break;
        }
        //LOG_DEBUG("TcpEchoSession sent an echo of %d bytes", (int)echoSize);
    }
    
    socket.close();
    LOG_INFO("End of TcpEchoServerSession::run");
}
void ConnectionThread::run()
{
    Debug() << "Thread started.";
    QTcpSocket sock;
    socketNoNagle(sockdescr);
    if (!sock.setSocketDescriptor(sockdescr)) {
        Error() << sock.errorString();
        return;
    }
    QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
    Log() << "Connection from peer " << remoteHostPort;
    QString line;
    forever {
        if (sock.canReadLine() || sock.waitForReadyRead()) {
            line = sock.readLine().trimmed();
            while (StimApp::instance()->busy()) {
                // special case case, stimapp is busy so keep polling with 1s intervals                
                Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
                sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
            }
            // normal case case, stimapp not busy,  proceed normally
            QString resp;
            resp = processLine(sock, line);
            if (sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "processLine() closed connection";
                break;
            }
            if (!resp.isNull()) {
                if (resp.length()) {
                    Debug() << "Sending: " << resp;
                    if (!resp.endsWith("\n")) resp += "\n";
					QByteArray data(resp.toUtf8());
                    int len = sock.write(data);
					if (len != data.length()) {
						Debug() << "Sent "  << len << " bytes but expected to send " << data.length() << " bytes!";
					}
                }
                Debug() << "Sending: OK";
                sock.write("OK\n");
            } else {
                Debug() << "Sending: ERROR";
                sock.write("ERROR\n");
            }            
        } else {
            if (sock.error() != QAbstractSocket::SocketTimeoutError 
                || sock.state() != QAbstractSocket::ConnectedState) {
                Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
                break;
            }
        }
    }
    Log() << "Connection ended (peer: " << remoteHostPort << ")";
    Debug() << "Thread exiting.";
}
void DesignerExternalEditor::processTerminated(const QString &binary)
{
    const ProcessCache::iterator it = m_processCache.find(binary);
    if (it == m_processCache.end())
        return;
    // Make sure socket is closed and cleaned, remove from cache
    QTcpSocket *socket = it.value();
    m_processCache.erase(it); // Note that closing will cause the slot to be retriggered
    if (debug)
        qDebug() << Q_FUNC_INFO << '\n' << binary << socket->state();
    if (socket->state() == QAbstractSocket::ConnectedState)
        socket->close();
    socket->deleteLater();
}
Exemple #8
0
void NetworkServer::slotConnectionEnded()
{
    for(int i=0; i < mTcpSockets.size(); i++)
    {
        QTcpSocket* socket = mTcpSockets.at(i);
        if(socket->state() == QAbstractSocket::ClosingState || socket->state() == QAbstractSocket::UnconnectedState)
        {
            qDebug() << "NetworkServer::slotConnectionEnded(): connection from" << socket->peerAddress() << socket->peerPort() << "closed, removing socket.";
            socket->disconnect();
            socket->deleteLater();
            mTcpSockets.removeAt(i);
        }
    }
}
Exemple #9
0
void MrimConnection::connected()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket*>(sender());
    Q_ASSERT(socket);
	SystemIntegration::keepAlive(socket);

    bool connected = false;

    switch (socket->state())
    {
    case QAbstractSocket::ConnectedState:
        connected = true;
        break;
    default:
        break;
    }

    QString address = Utils::toHostPortPair(socket->peerAddress(),socket->peerPort());

    if (!connected)
    {
        debug()<<"Connection to server"<<qPrintable(address)<<"failed! :(";
        return;
    }
    else
    {
        debug()<<"Connected to server"<<qPrintable(address);

        if (socket == p->IMSocket()) //temp
        {
            sendGreetings();
        }
    }
}
Exemple #10
0
void ClientThread::run()
{
    QTcpSocket tcpSocket;
    if (!tcpSocket.setSocketDescriptor(m_socketDescriptor)) {
        qWarning() << ":(((";
        emit error(tcpSocket.error());
        return;
    }

    m_running = true;

    QString command, response;

    // Send greetings
    tcpSocket.write("OK MPD 0.12.2\n");

    while (m_running && (tcpSocket.state() == QAbstractSocket::ConnectedState)) {
        m_running = tcpSocket.waitForReadyRead();   // Wait for command, 
                                                    // if none is received until timeout
                                                    // (default 30 seconds, stop running).

        command = QString(tcpSocket.readLine()).trimmed();
       
        qDebug() << command;

        tcpSocket.write(parseCommand(command).toLocal8Bit());
    }

    tcpSocket.disconnectFromHost();
}
Exemple #11
0
void Server::recieveConnection()
{
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    QString client_ip = clientConnection->peerAddress().toString();
    quint32 client_ip_int = clientConnection->peerAddress().toIPv4Address();

    emit write_message(tr("New connection from IP: %1").arg(client_ip));

    if (sockets->contains(client_ip_int)) {
        QTcpSocket *oldClientConnection = (QTcpSocket*) sockets->value(client_ip_int);
        if (oldClientConnection && oldClientConnection->state() != QAbstractSocket::UnconnectedState) {
            oldClientConnection->disconnectFromHost();
        }
        sockets->remove(client_ip_int);
    }

    sockets->insert(client_ip_int, clientConnection);

    connect(clientConnection, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(clientConnection, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(recieveData()));
    connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
Exemple #12
0
void HttpServer :: readClient()
{
  if (disabled) return;
  QTcpSocket *socket = (QTcpSocket*)sender();
  if( socket->canReadLine()) {

    QString request = socket->readLine();
    QStringList tokens = request.split(QRegExp("[ \r\n][ \r\n]*"));

    if( tokens[0] == "GET") {
      d->engine.globalObject().setProperty("token", tokens[1]);      
      QScriptValue reply = d->engine.evaluate("reply(token)");
      
      QTextStream os(socket);
      os.setAutoDetectUnicode(true);
      os << reply.toString().toUtf8();
      
      socket->close();
      
      QtServiceBase::instance()->logMessage("Wrote index.html");
      
      if(socket->state() == QTcpSocket::UnconnectedState) {
        delete socket;
        QtServiceBase::instance()->logMessage("Conncetion closed");
        
      }
    }
  }
}
Exemple #13
0
/**
 * @details
 * Send dataSupport Information to connected clients
 */
void TCPConnectionManager::_sendNewDataTypes()
{
    DataSupportResponse res( types() );

    clients_t clientListCopy;
    {
        // control access to the _clients
        QMutexLocker locker(&_mutex);
        clientListCopy = _clients[_dataSupportStream];
    }

    // iterate over all clients subscribed to the data support channel
    for(int i = 0; i < clientListCopy.size(); ++i ) {

        QTcpSocket* client =  clientListCopy[i];

        // Send data to client
        try {
            //std::cout << "Sending to:" << client->peerName().toStdString() << std::endl;
            Q_ASSERT( client->state() == QAbstractSocket::ConnectedState );
            _protocol->send(*client, res);
            client->flush();
            //std::cerr <<  "TCPConnectionManager: sending newdata types to client" << std::endl;
        }
        catch ( ... )
        {
            // kill the client if anything goes wrong
            std::cerr <<  "TCPConnectionManager: failed to send data to client" << std::endl;
            _killClient(client);
        }
    }
}
Exemple #14
0
void QServerThread::run()
{
   QTcpSocket qsocket;
   if( qsocket.setSocketDescriptor( sd) == false)
   {
      AFERROR("QThreadServer::run: Can't set socket descriptor.\n");
      return;
   }

   af::Msg* msg = new af::Msg;
   if( afqt::recvMessage( &qsocket, msg))
   {
      if( recvMessage_handler_ptr == NULL )
      {
         emit newmsg( msg);
      }
      else
      {
         if( recvMessage_handler_ptr( &qsocket, msg) == false)
         {
            emit newmsg( msg);
         }
      }
   }
   qsocket.disconnectFromHost();
   if( qsocket.state() != QAbstractSocket::UnconnectedState ) qsocket.waitForDisconnected();
}
Exemple #15
0
void HttpDaemon::readClient()
{
    QTcpSocket* socket = (QTcpSocket*)sender();
    if (socket->canReadLine())
    {
        QTextStream os(socket);
        os.setAutoDetectUnicode(true);
        os << "HTTP/1.0 200 Ok\r\n"
            "Content-Type: text/html; charset=\"utf-8\"\r\n"
            "\r\n";

        QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));

        QRegExp pathPattern("^/websocket\\.(html|js)$");
        if (pathPattern.exactMatch(tokens[1]))
        {
            QFile file (":" + pathPattern.capturedTexts()[0]);
            file.open(QFile::ReadOnly);
            os << file.readAll()
               << "\n\n";
        }
        else
        {
            os << "<h1>Nothing to see here</h1>\n\n";
        }

        socket->close();

        if (socket->state() == QTcpSocket::UnconnectedState)
            delete socket;
    }
}
void TCPConnectionManagerTest::test_send()
{
    // Use Case:
    // client requests a connection
    // expect client to be registered for any data
    StreamDataRequest req;
    DataSpec require;
    require.addStreamData("testData");
    req.addDataOption(require);

    QTcpSocket* client = _createClient();
    _sendRequest( client, req );
    QCoreApplication::processEvents();
    CPPUNIT_ASSERT_EQUAL( 1, _server->clientsForStream("testData") );
    TestDataBlob blob;
    blob.setData("sometestData");
    _server->send("testData",&blob);
    sleep(1);

    CPPUNIT_ASSERT( client->state() == QAbstractSocket::ConnectedState );
    boost::shared_ptr<ServerResponse> r = _clientProtocol->receive(*client);
    CPPUNIT_ASSERT( r->type() == ServerResponse::Blob );
    DataBlobResponse* res = static_cast<DataBlobResponse*>(r.get());
    CPPUNIT_ASSERT( res->dataName() == "testData" );
    CPPUNIT_ASSERT( res->blobClass() == "TestDataBlob" );
    TestDataBlob recvBlob;
    recvBlob.deserialise(*client, res->byteOrder());
    CPPUNIT_ASSERT(recvBlob == blob);

}
bool TcpDecorator::execute(Request &req, QIODevice &io)
{
    form(req);
    QTcpSocket* s = dynamic_cast<QTcpSocket*>(&io);
    if(s->state()==QTcpSocket::ConnectedState) {
        s->write(req.getBody());
        s->waitForBytesWritten(100);


        QByteArray rxData;

        int wait = 15;
        if(req.getWaitTime()!=0) wait = req.getWaitTime();

        for(int i=0;i<wait/100;i++) {
            if(s->waitForReadyRead(100)) {
                rxData=s->readAll();
                break;
            }
        }
        if(rxData.count()==1+req.getDataNumber()+2) {
            req.updateRdData(rxData);
            req.setAnswerData(rxData);
            if(checkAnAnswer(req)) {
                getAnAnswer(req);
                return true;
            }
        }
    }
    req.setAnswerData(QByteArray());
    return false;
}
static QByteArray readLine(QTcpSocket &sock)
{
    while (!sock.canReadLine() && sock.waitForReadyRead());
    if (sock.state() != QAbstractSocket::ConnectedState)
        return QByteArray();
    return sock.readLine();
}
Exemple #19
0
/* perform the operations for a frame:
 *   - check to see if the connections are still alive (checkAlive)
 *      - this will emit connectionsChanged if there is a any change in the connection status
 *   - grab a text stream of the current model data ( stream << *subjectList )
 *   - put the text stream on the wire s->write(...)
*/
void MyServer::process()
{
    stopProfile("Other");

    working = true;

    startProfile("checkAlive");
    int alive = checkAlive();
    stopProfile("checkAlive");

    if(alive > 0)
    {
        startProfile("Serve");

        count++;
        QString buffer;
        QTextStream stream(&buffer);
        // The following operation is threadsafe.
        startProfile("Fetch");
        subjectList->read(stream, true);
        stopProfile("Fetch");

        startProfile("Wait");
        listMutex.lock();
        stopProfile("Wait");

        // for each connection
        for(QList<ServerConnection *>::iterator i =  connections.begin(); i != connections.end(); i++)
        {
            QTcpSocket *s = (*i)->socket;
            if(s->state() != QAbstractSocket::ConnectedState) continue;

            QString d = QString("%1\nEND\r\n").arg(buffer);

            startProfile("Write");
            int written = s->write(d.toUtf8());
            stopProfile("Write");

            if(written == -1)
            {
                emit outMessage(QString(" Error writing to %1").arg(s->peerAddress().toString()));
            }
            else
            {
                s->flush();
            }
        }

        listMutex.unlock();

        stopProfile("Serve");
    }

    working = false;


    startProfile("Other");


}
/*!
 * @brief
 * this thread will read text from the Network
 * and create events to write that text.
 */
void NetHandler::run()
{
	s = new QTcpServer();
	if (!s->listen(QHostAddress(addr), port))
	{
		qDebug() << "listening on " << addr.toString() << ":" << port << " failed";
		delete s;
		return;
	}
	char b[1024]; // buffer
	int n;        // bytes read
	bool state;
	QTcpSocket *socket = NULL;
	while (1)
	{
		state = s->waitForNewConnection(1000);
		// check if we should stop the loop
		if (sd.terminating)
		{
			s->close();
			delete s;
			return;
		}
		if (!state)
			continue;
		
		socket = s->nextPendingConnection();
		qDebug() << "Yay! Someone connected at " << QDateTime::currentDateTime();
		
		while(1)
		{
			state = socket->waitForReadyRead(1000);
			// check if we should stop the loop
			if (sd.terminating)
			{
				s->close();
				delete socket;
				delete s;
				return;
			}
			if (!state)
				if (socket->state() == QAbstractSocket::UnconnectedState)
				{
					qDebug() << "Nay! Someone disconnected at " << QDateTime::currentDateTime();
					break;
				}
				else
					continue;
			
			while (socket->bytesAvailable())
			{
				n = socket->read(b, 1016);
				actOnData(b, n);
			}	
		}
		delete socket;
	}
}
Exemple #21
0
void HttpDaemon :: readClient()
{
  QTcpSocket *socket = (QTcpSocket*) sender();
  if (socket->canReadLine()) {
    QStringList tokens = QString(socket->readLine()).split(QRegExp("[ \r\n][ \r\n]*"));
    handleToken(tokens, socket);
    if (socket->state() == QTcpSocket::UnconnectedState) {
      delete socket;
    }
  }
}
QTcpSocket* TCPConnectionManagerTest::_createClient() const
{
   // Create a client and connect it to the server
   QTcpSocket* tcpSocket = new QTcpSocket;
   tcpSocket->connectToHost( QHostAddress::LocalHost, _server->serverPort() );
   if (!tcpSocket->waitForConnected(5000) || tcpSocket->state() == QAbstractSocket::UnconnectedState)
   {
       delete tcpSocket;
       tcpSocket = 0;
       CPPUNIT_FAIL("Client could not connect to server");
   }
   return tcpSocket;
}
Exemple #23
0
void ListeningTests::TestConnectToServer() {
    CServer vServer(new CReceiverMockFactory());
    vServer.Run();
    QVERIFY(vServer.isListening());

    QTcpSocket vSocket ;
    int vPortNumber {vServer.serverPort()};
    vSocket.connectToHost(QHostAddress("127.0.0.1"), vPortNumber);

    bool vConnectionEstablished {vSocket.waitForConnected()};
    QVERIFY(vConnectionEstablished);
    QVERIFY( vSocket.state() == QTcpSocket::ConnectedState );
}
Exemple #24
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::ipv4LoopbackPerformanceTest()
{
    QFETCH_GLOBAL(bool, setProxy);
    if (setProxy)
        return;

    QTcpServer server;
    QVERIFY(server.listen(QHostAddress::LocalHost));

    QVERIFY(server.isListening());

    QTcpSocket clientA;
    clientA.connectToHost(QHostAddress::LocalHost, server.serverPort());
    QVERIFY(clientA.waitForConnected(5000));
    QVERIFY(clientA.state() == QAbstractSocket::ConnectedState);

    QVERIFY(server.waitForNewConnection());
    QTcpSocket *clientB = server.nextPendingConnection();
    QVERIFY(clientB);

    QByteArray buffer(16384, '@');
    QTime stopWatch;
    stopWatch.start();
    qlonglong totalWritten = 0;
    while (stopWatch.elapsed() < 5000) {
        QVERIFY(clientA.write(buffer.data(), buffer.size()) > 0);
        clientA.flush();
        totalWritten += buffer.size();
        while (clientB->waitForReadyRead(100)) {
            if (clientB->bytesAvailable() == 16384)
                break;
        }
        clientB->read(buffer.data(), buffer.size());
        clientB->write(buffer.data(), buffer.size());
        clientB->flush();
        totalWritten += buffer.size();
        while (clientA.waitForReadyRead(100)) {
            if (clientA.bytesAvailable() == 16384)
                break;
        }
        clientA.read(buffer.data(), buffer.size());
    }

    qDebug("\t\t%s: %.1fMB/%.1fs: %.1fMB/s",
           server.serverAddress().toString().toLatin1().constData(),
           totalWritten / (1024.0 * 1024.0),
           stopWatch.elapsed() / 1000.0,
           (totalWritten / (stopWatch.elapsed() / 1000.0)) / (1024 * 1024));

    delete clientB;
}
void HttpServer::readClient()
{
	if (!m_accept)
		return;

	QTcpSocket* socket = (QTcpSocket*)sender();
	try
	{
		if (socket->canReadLine())
		{
			QString hdr = QString(socket->readLine());
			QVariantMap headers;
			if (hdr.startsWith("POST") || hdr.startsWith("GET"))
			{
				QUrl url(hdr.split(' ')[1]);
				QString l;
				do
				{
					l = socket->readLine();
					//collect headers
					int colon = l.indexOf(':');
					if (colon > 0)
						headers[l.left(colon).trimmed().toLower()] = l.right(l.length() - colon - 1).trimmed();
				}
				while (!(l.isEmpty() || l == "\r" || l == "\r\n"));

				QString content = socket->readAll();
				std::unique_ptr<HttpRequest> request(new HttpRequest(this, std::move(url), std::move(content), std::move(headers)));
				clientConnected(request.get());
				QTextStream os(socket);
				os.setAutoDetectUnicode(true);
				QString q;
				///@todo: allow setting response content-type, charset, etc
				os << "HTTP/1.0 200 Ok\r\n";
				if (!request->m_responseContentType.isEmpty())
					os << "Content-Type: " << request->m_responseContentType << "; ";
				os << "charset=\"utf-8\"\r\n\r\n";
				os << request->m_response;
			}
		}
	}
	catch(...)
	{
		delete socket;
		throw;
	}
	socket->close();
	if (socket->state() == QTcpSocket::UnconnectedState)
		delete socket;
}
Exemple #26
0
  void ExitTunnel::TcpProxyStateChanged(QAbstractSocket::SocketState)
  {
    qDebug() << "SOCKS Socket changed state";

    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if(!socket) {
      qWarning("SOCKS Illegal call to ProxyStateChanged()");
      return;
    }
    if(socket->state() == QAbstractSocket::ConnectedState) {
      qDebug() << "SOCKS Socket state is connected";
      TcpWriteBuffer(socket);
    }
  }
Exemple #27
0
// Check to see if all connections are alive, if not remove them from the list
// returns number of active connections.
int MyServer::checkAlive()
{
    listMutex.lock();

    bool done = false;
    bool modified = false;
	int  ret = 0;

    while(!done)
    {
        done = true;

        for(QList<ServerConnection*>::iterator i = connections.begin(); i != connections.end(); i++)
        {
            QTcpSocket *s = (*i)->socket;
            if(s->state() == QAbstractSocket::UnconnectedState)
            {
                emit outMessage(QString("Disconnected: %1").arg((*i)->str()));
                done = false;
                modified = true;
                delete *i;
                connections.erase(i);
                break;
            }

			if(s->state() == QAbstractSocket::ConnectedState)
				ret++;
        }

    }
    listMutex.unlock();

    if(modified) 
		emit connectionsChanged();

	return ret;
}
void TCPConnectionManagerTest::test_dataSupportedRequest()
{
    // Use Case:
    // Send a dataSupport request with no data
    // Expect: stream to return a DataSupportResponse
    // and add us to the datasupport stream
    QString streamInfo("__streamInfo__");
    DataSupportRequest req;
    QTcpSocket* client = _createClient();
    CPPUNIT_ASSERT_EQUAL( 0, _server->clientsForStream(streamInfo) );
    _sendRequest( client, req );
    QCoreApplication::processEvents();
    CPPUNIT_ASSERT_EQUAL( 1, _server->clientsForStream(streamInfo) );

    sleep(1);
    QCoreApplication::processEvents();
    CPPUNIT_ASSERT( client->state() == QAbstractSocket::ConnectedState );
    boost::shared_ptr<ServerResponse> r = _clientProtocol->receive( *client );
    CPPUNIT_ASSERT( r->type() == ServerResponse::DataSupport );

    // Use case:
    // New stream type arrives
    // Expect:
    // to receive a new DataRequest with the new data
    QString stream1("stream1");
    TestDataBlob blob;
    blob.setData("stream1Data");
    _server->send(stream1,&blob);
    sleep(1);
    QCoreApplication::processEvents();

    r = _clientProtocol->receive(*client);
    CPPUNIT_ASSERT( r->type() == ServerResponse::DataSupport );
    DataSupportResponse* res = static_cast<DataSupportResponse*>(r.get());
    CPPUNIT_ASSERT_EQUAL( 1, res->streamData().size() );
    CPPUNIT_ASSERT( res->streamData().contains(stream1) );

    // Use case:
    // Existing stream type arrives
    // Expect:
    // not to receive a new DataRequest
    _server->send(stream1,&blob);
    sleep(1);
    QCoreApplication::processEvents();

    r = _clientProtocol->receive(*client);
    CPPUNIT_ASSERT( r->type() != ServerResponse::DataSupport );
}
Exemple #29
0
void HttpDaemon::readClient()
{
    if (disabled)
        return;

    // This slot is called when the client sent data to the server. The
    // server looks if it was a get request and sends a very simple HTML
    // document back.
    QTcpSocket* socket = (QTcpSocket*)sender();
    if (socket->canReadLine()) {
        QByteArray data = socket->readLine();
        QStringList tokens = QString(data).split(QRegExp("[ \r\n][ \r\n]*"));
        qDebug() << "incoming data" << tokens[1];
        QUrl url("http://foo.bar" + tokens[1]);
        QUrlQuery query(url);
        qDebug() << "query is" << url.path();
        if (url.path() == "/setstate") {
            emit setState(StateTypeId(query.queryItems().first().first), QVariant(query.queryItems().first().second));
        } else if (url.path() == "/generateevent") {
            qDebug() << "got generateevent" << query.queryItemValue("eventtypeid");
            emit triggerEvent(EventTypeId(query.queryItemValue("eventtypeid")));
        } else if (url.path() == "/actionhistory") {
            QTextStream os(socket);
            os.setAutoDetectUnicode(true);
            os << generateHeader();
            for (int i = 0; i < m_actionList.count(); ++i) {
                os << m_actionList.at(i).first.toString() << '\n';
            }
            socket->close();
            return;
        } else if (url.path() == "/clearactionhistory") {
            m_actionList.clear();
        }
        if (tokens[0] == "GET") {
            QTextStream os(socket);
            os.setAutoDetectUnicode(true);
            os << generateWebPage();
            socket->close();

            qDebug() << "Wrote to client";

            if (socket->state() == QTcpSocket::UnconnectedState) {
                delete socket;
                qDebug() << "Connection closed";
            }
        }
    }
}
void TestHTTPServer::readyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (!socket || socket->state() == QTcpSocket::ClosingState)
        return;

    if (!m_directories.isEmpty()) {
        serveGET(socket, socket->readAll());
        return;
    }

    if (m_state == Failed || (m_waitData.body.isEmpty() && m_waitData.headers.count() == 0)) {
        qWarning() << "TestHTTPServer: Unexpected data" << socket->readAll();
        return;
    }

    if (m_state == AwaitingHeader) {
        QByteArray line;
        while (!(line = socket->readLine()).isEmpty()) {
            line.replace('\r', "");
            if (line.at(0) == '\n') {
                m_state = AwaitingData;
                m_data += socket->readAll();
                break;
            } else {
                if (!m_waitData.headers.contains(line)) {
                    qWarning() << "TestHTTPServer: Unexpected header:" << line
                               << "\nExpected headers: " << m_waitData.headers;
                    m_state = Failed;
                    socket->disconnectFromHost();
                    return;
                }
            }
        }
    }  else {
        m_data += socket->readAll();
    }

    if (!m_data.isEmpty() || m_waitData.body.isEmpty()) {
        if (m_waitData.body != m_data) {
            qWarning() << "TestHTTPServer: Unexpected data" << m_data << "\nExpected: " << m_waitData.body;
            m_state = Failed;
        } else {
            socket->write(m_replyData);
        }
        socket->disconnectFromHost();
    }
}