void RemoteConnection::dataReceived()
{
    QTcpSocket* socket = this->socket();
    if (!socket)
        return;

    QDataStream stream(socket);

    while (socket->bytesAvailable()) {
        if (m_state == WaitingForLength) {
            if (socket->bytesAvailable() < (qint64) sizeof(qint32))
                return;

            stream >> m_length;
            m_length -= sizeof(qint32);
            m_state = WaitingForData;
        }

        if (m_state == WaitingForData) {
            if (socket->bytesAvailable() < m_length)
                return;

            m_state = WaitingForLength;
            QByteArray data = socket->read(m_length);
            Q_ASSERT(data.length() == m_length);

            QBuffer buffer(&data);
            buffer.open(QIODevice::ReadOnly);
            QDataStream stream(&buffer);
            qint32 id;
            stream >> id;

            std::unique_ptr<RemoteCommand> command = RemoteCommand::create(static_cast<CommandType>(id));
            command->decode(stream);
            protocolDebug() << qPrintable(QTime::currentTime().toString(QString::fromUtf8("hh:mm:ss.zzz")))
                               << ": Received " << qPrintable(id);

            emit gotCommand(*command);
        }
    }
}
Example #2
0
void HttpRequest::readBody(QTcpSocket& socket) {
      Q_ASSERT(expectedBodySize != 0);
      if (boundary.isEmpty()) {
            // normal body, no multipart
#ifdef SUPERVERBOSE
            qDebug("HttpRequest: receive body");
#endif
            int toRead = expectedBodySize - bodyData.size();
            QByteArray newData = socket.read(toRead);
            currentSize += newData.size();
            bodyData.append(newData);
            if (bodyData.size() >= expectedBodySize) {
                  status = complete;
                  }
            }
      else {
            // multipart body, store into temp file
#ifdef SUPERVERBOSE
            qDebug("HttpRequest: receiving multipart body");
#endif
            if (!tempFile.isOpen()) {
                  tempFile.open();
                  }
            // Transfer data in 64kb blocks
            int fileSize = tempFile.size();
            int toRead = expectedBodySize - fileSize;
            if (toRead > 65536) {
                  toRead = 65536;
                  }
            fileSize += tempFile.write(socket.read(toRead));
            if (fileSize >= maxMultiPartSize) {
                  qWarning("HttpRequest: received too many multipart bytes");
                  status = abort;
                  }
            else if (fileSize >= expectedBodySize) {
#ifdef SUPERVERBOSE
                  qDebug("HttpRequest: received whole multipart body");
#endif
                  tempFile.flush();
                  if (tempFile.error()) {
                        qCritical("HttpRequest: Error writing temp file for multipart body");
                        }
                  parseMultiPartFile();
                  tempFile.close();
                  status = complete;
                  }
            }
      }
Example #3
0
void ThreadJoueurs::run()
{
    QTcpSocket unSocket;


    unSocket.setSocketDescriptor(m_socketDescriptor);
    if(unSocket.waitForConnected(1000))
    {
        while(unSocket.ConnectedState)         //.waitForReadyRead(1000))
        {
            baRXInfos=unSocket.read(unSocket.bytesAvailable());
            if(baRXInfos.left(1) == "&")    //code de connection des joueurs
            {
                unSocket.write(baTXInfos.append(cNoJ));     //assignation du numero
                baTXInfos = TXInfosToJoueurs(m_tNouvellePartie,9);  // trame de debut de partie (= NouvellePartie)
            }
            else
            {
                RXInfosFmJoueurs(baRXInfos);                //recoit {'#', JnX, JnY}
                baTXInfos = TXInfosToJoueurs(m_txInfos,9);  //repond trame {code, balle X, balle Y, J1X, J1Y, J2X, J2Y, ScoreA, ScoreB}
            }                                               // code = '#' (normale), '$' (gagnant), '%' (Nouvelle Balle)
            unSocket.write(baTXInfos);
            unSocket.waitForBytesWritten(10);
        }
    }
    unSocket.disconnectFromHost();
    unSocket.close();

}
Example #4
0
void TcpServer::OnClientData()
{
	QTcpSocket* connection = qobject_cast<QTcpSocket*>(sender());
	quint64 bufferSize = 2048;
	char buffer[bufferSize];
	quint64 dataRead = 0;

	dataRead = connection->read(buffer, bufferSize);
	buffer[dataRead] = 0;

	//qDebug() << "[WEB] Incoming data[" << dataRead << "]: " << buffer;

	QString value;

	//Check if it's a Flash policy request, only the first time
	//if (this->justConnected == true) {
		value = buffer;
		if (value.contains("<policy-file-request/>")) {
			connection->write(XML_CROSS_DOMAIN);
			qDebug() << "[TcpServer::OnClientData] Sent xml cross domain file";
			//this->justConnected = false;
			return;
		}
		else if ( value.contains("HTTP") ) {	//then its HTTP request

			QString response;

			//Check the data and create response
			DataHandler(value, response);
			HttpResponse httpHeader(response);

			connection->write( httpHeader.GetHeader() );
			connection->write( response.toUtf8().constData() );

			connection->close();
		}
	//}
	//Other requests that are not http requests or posts
	// This may be deleted
	//else {
		else if (value == "CORE") {
			XmlParser xml(buffer, dataRead);
			int action = CEMI_ACTION_WRITE;
			int groupAddr = 0;

			xml.GetValue("cmd", value);
			if (value == "write") action = CEMI_ACTION_WRITE;
			else if (value == "read") action = CEMI_ACTION_READ;

			xml.GetValue("groupAddr", value);
			groupAddr = Common::GroupAddrToInt(value);
			//qDebug() << "groupAddr: " << value;

			xml.GetValue("value", value);

			emit TcpServerData((int)action, groupAddr, value);
		}
	//}
	//this->justConnected = false;
}
Example #5
0
void Tunneld::onTcpReadyRead()
{
    QTcpSocket *sock = (QTcpSocket*)sender();
    ToxTunChannel *chan = this->m_sock_chans[sock];

    if (chan->m_enpeer->state == ENET_PEER_STATE_CONNECTED) {
        while (sock->bytesAvailable() > 0) {
            // QByteArray ba = sock->readAll();
            QByteArray ba = sock->read(567);
            if (ba.length() >= 1371) {
                qDebug()<<"too long data packet.";
            }
        
            ENetPacket *packet = enet_packet_create(ba.data(), ba.length(), ENET_PACKET_FLAG_RELIABLE);

            // enet_packet_resize(packet, 13);
            // strcpy((char*)&packet->data[9], "foo");
    
            uint8_t chanid = 0;
            ENetPeer *enpeer = chan->m_enpeer;
            // enet_peer_send(enpeer, chanid, packet);
            m_enpoll->sendPacket(enpeer, chanid, packet);
        }
    }

}
Example #6
0
//worker in thread
void CommThrd::run()
{
    QTcpSocket qtcpSelfClient;
    QHostAddress qhostLocal("127.0.0.1");
    qtcpSelfClient.connectToHost(qhostLocal, 35791);
    //connect successfully
    if(qtcpSelfClient.waitForConnected())
    {
        //send request message !!!need to be modified
        //replace \n to \r\n
        QRegExp qreTemp("\\n");
        mpqstrRequ->replace(qreTemp, "\r\n");
        QByteArray qbyaRequ = mpqstrRequ->toAscii();
        int i=qtcpSelfClient.write(qbyaRequ);
        if(i==-1)
            return;
            //QMessageBox::information(this, "Composer Error", "Can't send request to localhost!");
        qtcpSelfClient.waitForBytesWritten();
        //read response
        int iAvail = 0;
        QByteArray qbyaResp;
        bool bReady = qtcpSelfClient.waitForReadyRead(30000);
        iAvail = qtcpSelfClient.bytesAvailable();
        qbyaResp = qtcpSelfClient.read(iAvail);
        delete mpqstrRequ;
        mpqstrRequ = new QString(qbyaResp);
        //post message to UI
        ERespAvail *pclsEvnt = new ERespAvail() ;
        qApp->postEvent((QObject*)(pwdMainWin->pwinComposer), pclsEvnt);
    }
        //QMessageBox::information(this, "Composer Error", "Can't connect to localhost!");
}
Example #7
0
bool Http::send(QString host, int port, QByteArray data, QByteArray &result, int timeout)
{
    QByteArray response;
    QTcpSocket socket;
    int numRead = 0;
    int numReadTotal = 0;
    char buffer[50];

    socket.connectToHost(QHostAddress(host),port);
    if (!socket.waitForConnected(timeout)) {
        return false;
    }

    socket.write(data);
    if (!socket.waitForBytesWritten(timeout))
    {
        return false;
    }

    forever {
        numRead  = socket.read(buffer, 50);
        numReadTotal += numRead;
        response.append(buffer,numRead);
        if (numRead == 0 && !socket.waitForReadyRead(timeout))
            break;
    }
    socket.disconnectFromHost();

    int header = response.indexOf("\r\n\r\n");
    if (header != -1) {
        result = response.mid(header+4);
    }
    return true;
}
Example #8
0
int MainWindow::getSensorTemperature(){
   // Get the server address and port from the settings dialog box
   int serverPort = this->dialog->getServerPort();  // get from the dialog box
   quint32 serverAddr = this->dialog->getIPAddress();   // from the dialog box
   QTcpSocket *tcpSocket = new QTcpSocket(this);    // create socket
   tcpSocket->connectToHost(QHostAddress(serverAddr), serverPort); // connect
   if(!tcpSocket->waitForConnected(1000)){    //wait up to 1s for a connection
      statusBar()->showMessage("Failed to connect to server...");
      return 1;
   }
   // Send the message "getTemperature" to the server
   tcpSocket->write("getTemperature");
   if(!tcpSocket->waitForReadyRead(1000)){    // wait up to 1s for the server
      statusBar()->showMessage("Server did not respond...");
      return 1;
   }
   // If the server has sent bytes back to the client
   if(tcpSocket->bytesAvailable()>0){
      int size = tcpSocket->bytesAvailable(); // how many bytes are ready?
      char data[20];                          // upper limit of 20 chars
      tcpSocket->read(&data[0],(qint64)size); // read the number of bytes rec.
      data[size]='\0';                        // termintate the string
      this->curTemperature = atof(data);      // string -> float conversion
      cout << "Received the data [" << this->curTemperature << "]" << endl;
   }
   else{
      statusBar()->showMessage("No data available...");
   }
   return 0;    // the on_updateTemperature() slot will update the display
}
Example #9
0
  void ExitTunnel::TcpReadFromProxy()
  {
    if(!_running) {
      qDebug("SOCKS read but not running");
      return;
    }

    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    if(!socket) {
      qWarning("SOCKS Illegal call to ReadFromClient()");
      return;
    }

    if(!CheckSession()) {
      qDebug("SOCKS read but no session");
      return;
    }
  
    do {
      QByteArray data = socket->read(64000);
      qDebug() << "SOCKS Read" << data.count() << "bytes from proxy socket";
      TcpResponsePacket resp(_table.IdForConnection(socket), data);
      //GetSession()->Send(resp.ToByteArray());
      //qDebug() << "SOCKS " << data;
      SendReply(resp.ToByteArray());
    } while(socket->bytesAvailable());

    qDebug() << "MEM active" << _table.Count();
  }
Example #10
0
void GameServer::onConnect()
{
    qDebug() << "CONNECTED";

    QTcpSocket* socket = _server->nextPendingConnection();
    socket->waitForReadyRead();

    qDebug() << socket->bytesAvailable();

    const int MaxLength = 1024;
    char buffer[MaxLength + 1];

    qint64 byteCount = socket->read(buffer, MaxLength);
    buffer[byteCount] = 0;

    qDebug() << buffer;

    const char* response =
        "HTTP/1.1 200 OK\r\n"
        "Connection: close\r\n"
        "Content-Type: text/html; charset=UTF-8\r\n"
        "\r\n"
        "<html><head><title>XPG Server</title></head>"
        "<body><p>Hello, World! Text is da bomb.</p></body>"
        "</html>"
        ;

    qDebug() << socket->write(response);

    socket->waitForBytesWritten();

    socket->close();
    delete socket;
}
void CDaemon::handleClientRead()
{
	QTcpSocket * socket = qobject_cast<QTcpSocket *>(sender());

	while(socket->bytesAvailable() > 8)
	{
		QDataStream stream(socket);
		quint64 size;

		stream >> size;
		if(socket->bytesAvailable() >= size)
		{
			QByteArray buffer(socket->read(size));
			QDataStream bStream(buffer);
			quint8 opcode;

			bStream >> opcode;
			switch(opcode)
			{
			case OPCODE_ADD:
				handleAdd(bStream); break;
			case OPCODE_REMOVE:
				handleRemove(bStream); break;
			case OPCODE_START:
				handleStart(bStream); break;
			case OPCODE_STOP:
				handleAbort(bStream); break;
			case OPCODE_QUEUE:
				handleQueue(bStream); break;
			default:
				qWarning() << "Unhandled packet:" << quint32(opcode); break;
			}
		}
	}
Example #12
0
/*!
 * @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;
	}
}
Example #13
0
static bool read(QTcpSocket &sock, char *ptr, qint64 sz)
{
    do {
        qint64 readBytes = sock.read(ptr, sz);
        ptr += readBytes;
        sz -= readBytes;
    } while(sz && sock.waitForReadyRead());
    return sz == 0;
}
Example #14
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");
}
Example #15
0
void KCToolServer::onSocketReadyRead()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket*>(QObject::sender());

	// Parse the first line
	if(!socket->property("firstLineRead").toBool())
	{
		QString line(socket->readLine());
		int sepPos1(line.indexOf(" "));
		int sepPos2(line.indexOf(" ", sepPos1+1));
		QString method(line.left(sepPos1));
		QString path(line.mid(sepPos1+1, sepPos2 - sepPos1 - 1));
		socket->setProperty("method", method);
		socket->setProperty("path", path);
		socket->setProperty("firstLineRead", true);
	}

	// Parse Headers!
	if(!socket->property("headerRead").toBool()) {
		QVariantMap headers(socket->property("headers").toMap());

		while(socket->canReadLine()) {
			QString line = QString(socket->readLine()).trimmed();

			// The header section is terminated by an empty line
			if(line == "") {
				socket->setProperty("headerRead", true);
				break;
			}

			// Split it up
			int sepPos(line.indexOf(":"));
			QString key(line.left(sepPos).trimmed());
			QString val(line.mid(sepPos+1).trimmed());
			headers.insertMulti(key, val);
		}

		socket->setProperty("headers", headers);
	}

	qint64 contentLength = socket->property("headers").toMap().value("Content-Length").toLongLong();
	// Read the body into a buffer
	if(socket->bytesAvailable()) {
		QByteArray buffer(socket->property("buffer").toByteArray());
		qint64 toRead = contentLength - buffer.size();
		buffer.append(socket->read(toRead));
		socket->setProperty("buffer", buffer);
		socket->setProperty("toRead", contentLength - buffer.size());

		// If we have a Content-Length (toLong() fails with 0)
		if(contentLength > 0 && buffer.size() >= contentLength)
			this->handleRequest(socket);
	} else if(contentLength == -1 || contentLength == 0) {
		this->handleRequest(socket);
	}
}
Example #16
0
void Server::readRequest(){
    cout<<"new request"<<endl;
    QTcpSocket* client = (QTcpSocket*)sender();
    char* buffer = new char[client->bytesAvailable()];
  	client->read(buffer, client->bytesAvailable());
    cout <<"request was: "<<buffer<< endl;
    rh = new RequestHandler(buffer);
    rh->respond(client);
    delete rh;
    delete buffer;
}
Example #17
0
void CameraDialog::newData()
{
    static QByteArray buf0;
    static bool isBegain = false;
    static uint frame_len =0;
    QTcpSocket* client = qobject_cast<QTcpSocket*>(sender());
    if (!client) return;

    qint64 bufLen = client->bytesAvailable();
    char *buf = new char[bufLen+1];
    if (!buf) return;
//qDebug() << "bytesAvailable: " << bufLen;
    qint64 readLen = client->read(buf, bufLen);
    qDebug() << "readLen" << readLen/* <<":" << buf*/;
    buf0.append(buf, bufLen);
    if(!isBegain){
        p_yuv = frame_yuv;
        frame_len = *(unsigned int*)buf0.data();qDebug() << "DataLen: " << frame_len;
//        frame_len = *(unsigned int*)buf;qDebug() << "datalen: " << frame_len;
        buf0.remove(0, 4);
//        memcpy(p_yuv, buf+sizeof(frame_len), readLen - sizeof(frame_len));

        isBegain = true;
    }
    else {
//        uint len;
//        if((p_yuv - frame_yuv + readLen) >= frame_len){
//            len = frame_len - (p_yuv - frame_yuv);
//            isBegain = false;
//            hav_video = true;
//            this->update();
//        }
//        else{
//            len = readLen;
//        }
//        memcpy(p_yuv, buf, len);
//        p_yuv += len;

        if(buf0.length() >= frame_len){
            memcpy(frame_yuv, buf0.left(frame_len).data(), frame_len);
            buf0.remove(0, frame_len);
            isBegain = false;
            hav_video = true;
            this->update();
        }
    }

    if(readLen > 16){
//        hav_video = true;
//        this->update();
    }
}
Example #18
0
void SFEQuery::Receive(QTcpSocket &socket)
{
    // QDataStream _in((QTcpSocket*)&socket);

    _in.setVersion(QDataStream::Qt_4_7);


    while(socket.bytesAvailable()<sizeof(quint32))
        socket.waitForReadyRead(1000);

    qDebug("reading %d",sizeof(quint32));
    QByteArray ba = socket.read(sizeof(quint32));
    _inblock.append(ba);

    _in >> _size;

    qDebug("cmd size: %d",_size);

   quint32 left = _size- sizeof(quint32);

    while(socket.bytesAvailable()<left){
        qDebug("2 available: %d",(int)socket.bytesAvailable());
        socket.waitForReadyRead(1000);
    }
    qDebug("reading: %d",left);

    QByteArray ba2 = socket.read(left);
    _inblock.append(ba2);
//    _in.skipRawData(sizeof(quint32));
    quint32 type;
    _in >> type;

    qDebug("got type: %d",type);

    if (_type!=SFEQuery::NOTYPE_TYPE && type!=(quint32)_type)
        qDebug("error type !=");
    _type=(SFEQuery::QueryType)type;
    doReceive();
}
Example #19
0
//read a BasicBlock from socket。Becuase of the nature of socket,the function will run sevral times to finish reading
bool receiveNormalBlock(BasicBlock* sb,QTcpSocket& tcpSocket,unsigned int &currentBlockSize){
    if(currentBlockSize==0){
        if(tcpSocket.bytesAvailable()<2*sizeof(unsigned int))
            return false;
        tcpSocket.read((char*)&currentBlockSize,sizeof(unsigned int));
        tcpSocket.read((char*)&sb->classid,sizeof(unsigned int));
        currentBlockSize -= sizeof(unsigned int);
        if(currentBlockSize==0)
            return true;
    }
    if(currentBlockSize>0){
        if(tcpSocket.bytesAvailable()>=currentBlockSize){
            sb->content += tcpSocket.read(currentBlockSize);
            currentBlockSize=0;
            return true;
        }
        unsigned int remain=tcpSocket.bytesAvailable();
        sb->content += tcpSocket.read(remain);
        currentBlockSize -=remain;
        return false;
    }
    return false;
}
Example #20
0
void CProxy::slotClientDataAvailable()
{
    QTcpSocket * from = qobject_cast<QTcpSocket *>( sender() );
    if ( from )
    {
        QTcpSocket * to = m_clientKey[ from ];
        if ( to )
        {
            qint64 available = from->bytesAvailable();
            m_buffer.resize( available );
            qint64 cnt = from->read( m_buffer.data(), available );
            to->write( m_buffer.data(), cnt );
        }
    }
}
Example #21
0
//read stream data from socket。Becuase of the nature of socket,the function will run sevral times to finish reading
//stream is often large-scale,so it must be processed while reading,otherwise the memory will run out
bool receiveStreamData(QDataStream &out,QTcpSocket& tcpSocket,long long &streamLength,unsigned short &blockLength){
    if(streamLength==0){   //don't know the size of stream,the ending-if is "shorter frame + FRAMELENGTH"
        if(blockLength==0){
            if(tcpSocket.bytesAvailable()<2)
                return false;
            tcpSocket.read((char*)&blockLength,sizeof(unsigned short));
        }
        while(true){
            if(tcpSocket.bytesAvailable()<blockLength+2)
                return false;
            if(blockLength!=0){
                QByteArray dat= tcpSocket.read(blockLength);
                out.writeRawData(dat.data(),dat.length());
            }
            unsigned short tmpLen;
            tcpSocket.read((char*)&tmpLen,sizeof(unsigned short));
            if(blockLength!=STREAMBLOCKSIZE && tmpLen==STREAMBLOCKSIZE)
                return true;
            blockLength=tmpLen;
        }
    }
    if(streamLength>0){
        if(tcpSocket.bytesAvailable()>=streamLength){
            QByteArray dat= tcpSocket.read(streamLength);
            out.writeRawData(dat.data(),dat.length());
            streamLength=0;
            return true;
        }
        qint64 remain=tcpSocket.bytesAvailable();
        QByteArray dat= tcpSocket.read(remain);
        out.writeRawData(dat.data(),dat.length());
        streamLength -=remain;
        return false;
    }
    return false;
}
Example #22
0
void SatelliteServer::incomingData( QObject *client )
{
   QTcpSocket *socket = static_cast<QTcpSocket*>(client);

   while( socket->bytesAvailable() > SATELLITE_PKGINFO_HEADER_SIZE )
   {
      SATELLITE_PKGINFO_HEADER_TYPE   header( 0 );

      socket->peek( (char*)(&header), SATELLITE_PKGINFO_HEADER_SIZE );
      header = qFromBigEndian( header );
      if( (header >> 32) != SATELLITE_PKGINFO_MAGIC_VALUE )
      {
         /* invalid data, flush */
         socket->readAll();
#if SATELLITESERVER_DEBUG
         emit debug( "s:got bad data, flushing" );
#endif
         break;
      }
      qint64 datasize = (header & 0xFFFFFFFF) +
         SATELLITE_PKGINFO_CHECKSUM_SIZE + SATELLITE_PKGINFO_HEADER_SIZE;
      if( socket->bytesAvailable() < datasize )
      {
         /* buffer incomplete, let the try at next signal */
#if SATELLITESERVER_DEBUG
         emit debug( "s:got incomplete data" );
#endif
         break;
      }
      QByteArray msg( socket->read( datasize ) );

#if SATELLITESERVER_DEBUG
      /* for debugging show raw message as hex dump */
      emit debug( QByteArray("s:from client: ") + msg.toHex() );
#endif
      for( int i = 0; i < mClientConnections.count(); i++ )
      {
         QTcpSocket *current = mClientConnections.at(i);
         if( current && (client != current) )
         {
            current->write( msg );
         }
      }
   }
}
Example #23
0
void Server::readRequest(){
    cout<<"new request"<<endl;
    QTcpSocket* client = (QTcpSocket*)sender();
    char* buffer = new char[client->bytesAvailable()];
  	client->read(buffer, client->bytesAvailable());
    cout <<"request was: "<<buffer<< endl;
    string s(buffer);
    //RequestHandler* rhh = new RequestHandler(s,client,db);
    MethodInterpreter method(s);
    if(method.isTA()){
        cout<<"ta request"<<endl;
        taRequest th(s);
        th.respond(client,db);
    }else{
        cout<<"instructor request"<<endl;
        instructorRequest ih(s);
        ih.respond(client, db);

    }
    delete buffer;
}
Example #24
0
void ServerThread::run(){                  // the main thread loop
    QTcpSocket clientSocket;               // the clientSocket object
    this->running = true;                  // the main thread loop bool flag
    if (!clientSocket.setSocketDescriptor(socketDescriptor)){ //set up socket
        qDebug() << "Failed to setup the Socket";  // debug output
    }
    while(running){                        // loop forever until flag changes
       if(!clientSocket.waitForReadyRead(1000)){ // wait for up to 1 sec.
           this->running = false;                // failed - exit the loop
       }
       while(clientSocket.bytesAvailable()>0)    // are bytes available?
       {
           int x = clientSocket.bytesAvailable();  // how many?
           qDebug() << "There are " << x << " bytes available"; //debug
           char data[2000];                // capacity for up to 2000 bytes
           x = (qint64) clientSocket.read(&data[0], (qint64) x);
           data[x] = '\0';                 // add null in case of print output
           this->parse(&data[0]);          // parse the XML string
       }
    }
    clientSocket.close();                  // if loop finished, close socket
    qDebug() << "The client just disconnected";    // debug output
}
Example #25
0
int main(int argv, char **args)
{
    QCoreApplication app(argv, args);

    QTcpSocket socket;
    socket.connectToHost("localhost", 1025);
    
//! [0]
    int numRead = 0, numReadTotal = 0;
    char buffer[50];

    forever {
	numRead  = socket.read(buffer, 50);

	// do whatever with array
	
	numReadTotal += numRead;
	if (numRead == 0 && !socket.waitForReadyRead()) 
	    break;
    }
//! [0]
    
    return app.exec();
}
void getActiveCellCenters(NDArray& cellCenterValues, const QString &hostName, quint16 port, const qint32& caseId, const QString& porosityModel)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(riOctavePlugin::connectTimeOutMilliSecs))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command = QString("GetActiveCellCenters %1 %2").arg(caseId).arg(porosityModel);
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(riOctavePlugin::qtDataStreamVersion);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2 * sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::shortTimeOutMilliSecs))
        {
            error((("Waiting for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 activeCellCount;
    quint64 byteCount;

    socketStream >> activeCellCount;
    socketStream >> byteCount;

    if (!(byteCount && activeCellCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    dim_vector dv;
    dv.resize(2);
    dv(0) = activeCellCount;
    dv(1) = 3;

    cellCenterValues.resize(dv);

    while (socket.bytesAvailable() < (qint64)(byteCount))
    {
        if (!socket.waitForReadyRead(riOctavePlugin::longTimeOutMilliSecs))
        {
            error((("Waiting for data: ") + socket.errorString()).toLatin1().data());
            return;
        }
        OCTAVE_QUIT;
    }

    quint64 bytesRead = 0;
    double* internalMatrixData = cellCenterValues.fortran_vec();
    bytesRead = socket.read((char*)(internalMatrixData), byteCount);

    if (byteCount != bytesRead)
    {
        error("Could not read binary double data properly from socket");
        octave_stdout << "Active cell count: " << activeCellCount << std::endl;
    }

    return;
}
Example #27
0
int tcp_ping(QStringList command) {
    qDebug() << "tcp_ping(" << command.join(" ") << ")" << endl;

    /**
     * Check input
     */
    QTextStream errorStream(stderr);

    if(command.size() != 3 || command.at(0)!="ping" || command.at(1)!="tcp" ) {

        errorStream << "Error: tcp_ping(" << command.join(" ") << ") is no valid call (ping tcp <ip_address> <port> rzv|max|random|default)" << endl;
        return 1;
    }

    QByteArray byteArray;

    /**
     * CIP for "rzv"
     */
    if(command.at(2)=="rzv") {
        qDebug() << "rzv" << endl;

        byteArray.append(QByteArray(42, '\0'));
     }

    /**
     * CIP for "default"
     */
    if(command.at(2)=="default") {
        qDebug() << "default" << endl;

        // Header: request (1), profile (1), version (1), channel (1)
        byteArray.append(QByteArray(4, '\0'));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4), port number (2), time (8), type (1), size (1)
        byteArray.append(QByteArray(16, '\0'));

        // Contextinformation: type (1), root-CIC (2), size (1)
        byteArray.append(QByteArray(4, '\0'));

        // Application: type (1), size (1)
        byteArray.append(QByteArray(2, '\0'));
     }

    /**
     * CIP for "max"
     */
    if(command.at(2)=="max") {
        qDebug() << "max" << endl;

        // Header: fix
        byteArray.append(QByteArray(34, '\0'));

        // Header: size (1)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));

        // Contextinformation: fix
        byteArray.append(QByteArray(2, '\0'));

        // Contextinformation: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255*2, '\0'));

        // Application Data: fix
        byteArray.append(QByteArray(0, '\0'));

        // Application Data: size (255)
        byteArray.append(QByteArray(QByteArray::fromHex("0xff")));
        byteArray.append(QByteArray(255, '\0'));


     }

    /**
     * CIP for "random"
     */
    if(command.at(2)=="random") {
        qDebug() << "random" << endl;

        QByteArray randValues;
        qsrand(QTime::currentTime().msec());
        for(int i=0; i <= 1064; i++) {
            randValues.append(qFloor(qrand()/CRN_RANDOM_DIVISOR));
        }


        int i = 0;
        quint8 rand;

        // Header: request (1)
        byteArray.append(randValues.at(i++));


        // Header: profile (1)
        byteArray.append(randValues.at(i++));


        // Header: version (1)
        byteArray.append(randValues.at(i++));


        // Header: channel (1)
        byteArray.append(randValues.at(i++));

        // Header: UUID (16)
        QUuid uuid;
        uuid = QUuid::createUuid();
        QByteArray uuid_arr = uuid.toRfc4122();

        for(int j=0; j<16;j++) {

            byteArray.append(uuid_arr.at(j));
        }

        // Header: Empty IP address (4) and port number (2)
        byteArray.append(QByteArray(6, '\0'));

        // Header: time (8)
        byteArray.append(QByteArray(8, '\0'));

        // Header: type (1)
        byteArray.append(randValues.at(i++));

        // Header: size (1) and data
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

        // Contextinformation: type (1)
        byteArray.append(randValues.at(i++));

        // Contextinformation: root-CIC (2)
        byteArray.append(randValues.at(i++));
        byteArray.append(randValues.at(i++));

        // Contextinformation: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand*2, rand));

        // Application: type (1)
        byteArray.append(randValues.at(i++));

        // Application: size (1)
        rand = randValues.at(i++);
        byteArray.append(rand);
        byteArray.append(QByteArray(rand, rand));

    } // rand

    /**
     * Sent via TCP
     */
    QTcpSocket *tcpSocket;
    tcpSocket = new QTcpSocket();
    QTextStream outStream(stdout);

    QString out;

    tcpSocket->abort();
    tcpSocket->connectToHost("127.0.0.1", 22365);

    qDebug() << "waitForConnected!";
    if (tcpSocket->waitForConnected(5000)) {

        qDebug() << "Connected!";
    }
    else {
        errorStream << "Error: tcp_ping(" << command.join(" ") << ") No connection available!" << endl;
        return 1;
    }

    out = QString("BytesWritten: %1").arg(tcpSocket->write(byteArray, byteArray.length()));

    qDebug() << out;

    int numRead = 0, numReadTotal = 0;
    char buffer[MAXMSG];

    forever {
        numRead  = tcpSocket->read(buffer, MAXMSG);
        qDebug() << "read buffer";

        qDebug() << buffer;

        numReadTotal += numRead;
        if (numRead == 0 && !tcpSocket->waitForReadyRead())
            break;
    }
    qDebug() << numReadTotal << " bytes red";

    tcpSocket->flush();
    tcpSocket->disconnectFromHost();
    tcpSocket->close();

    outStream << out << endl;

    return 0;
}
Example #28
0
/* Function that is called whenever there is data ready to be processed.
 * This function should block until all data for the chunk has been read from
 * the device.
 */
void StreamChunker::next(QIODevice* device)
{
    // Note:
    // The next() function is slowed down initially by allocating the
    // data chunks.
    // It is probably best therefore, when running the benchmark, to make sure
    // all chunks are allocated before the timing starts.

    QTcpSocket* socket = static_cast<QTcpSocket*>(device);
    quint64 totalBytesRead = 0;
    quint64 bytesRead = 0;

    // Header values.
    quint32 packetSize = 0;
    quint32 packetCounter = 0;
    quint32 packetTime = 0;
    qint32 numPackets = 0;
    qint32 reportInterval = 0;
    size_t headerSize = 3*sizeof(quint32) + 2*sizeof(qint32);

    // Read header values.
    while (isActive() && totalBytesRead != headerSize)
    {
        while (socket->bytesAvailable() < (qint64)(headerSize)) {
            socket->waitForReadyRead(-1);
        }
        bytesRead = socket->read((char*)&packetSize, (qint64)sizeof(quint32));
        totalBytesRead+=bytesRead;
        bytesRead = socket->read((char*)&packetCounter, (qint64)sizeof(quint32));
        totalBytesRead+=bytesRead;
        bytesRead = socket->read((char*)&packetTime, (qint64)sizeof(quint32));
        totalBytesRead+=bytesRead;
        bytesRead = socket->read((char*)&numPackets, (qint64)sizeof(qint32));
        totalBytesRead+=bytesRead;
        bytesRead = socket->read((char*)&reportInterval, (qint64)sizeof(qint32));
        totalBytesRead+=bytesRead;
    }

    //
    // Writable chunks are obtained using the getDataStorage() method
    // using the the following priority:
    //
    // 1) A Pre-allocated chunk in the buffer that has already been served
    //    and has been marked for reuse.
    // 2) Allocating a new chunk in the buffer if space allows.
    // 3) Overwriting the oldest chunk in the buffer that matches the space
    //    requirements.
    //
    // If none of these conditions can be met, an invalid chunk is returned.
    //

    // If there are no usable chunks, i.e. the buffer is full we will
    // be overwriting chunks.
#if 1
    if (numUsableChunks(packetSize) == 0) {
        ++totalOverwriteCounter_;
        ++intervalOverwriteCounter_;
    }
#endif

    // Ask the data manager for a writable data chunk and get its data pointer.
    pelican::WritableData chunk = getDataStorage(packetSize);

    // Check chunk->isValid() before proceeding!
    if (!chunk.isValid()) {
        QString error = "StreamChunker::next(): Unable to get a valid chunk. ";
        if (packetSize > maxChunkSize()) {
            error += QString(
                    "\n== The requested packet size is greater than the maximum"
                    "\n== chunk size allowed by the buffer.");
        }
        throw error;
    }

    // Extract the data pointer from the chunk
    char* chunkPtr = (char*)chunk.ptr();

    // Write the header into the chunk.
    quint32* header1 = reinterpret_cast<quint32*>(chunkPtr);
    header1[0] = packetSize;
    header1[1] = packetCounter;
    header1[2] = packetTime;
    qint32* header2 = reinterpret_cast<qint32*>(chunkPtr+3*sizeof(quint32));
    header2[0] = numPackets;
    header2[1] = reportInterval;

    // NOTE Setting the read buffer size may have an impact on performance.
#if 0
    socket->setReadBufferSize(2*1024*1024);
#endif

    // NOTE The minimum read size has an impact on performance and has not
    // been optimised.
    quint64 minReadSize = 1024;//2*1024*1024; // bytes

    // Read data block directly into the chunk.
    quint64 dataRemaining = packetSize - headerSize;
    while (isActive() && dataRemaining > 0)
    {
        if (dataRemaining < minReadSize) minReadSize = dataRemaining;

        while (socket->bytesAvailable() < (qint64)minReadSize) {
            socket->waitForReadyRead(-1);
        }

        bytesRead = socket->read(chunkPtr+totalBytesRead, dataRemaining);
        totalBytesRead+=bytesRead;
        dataRemaining-=bytesRead;
    }

    chunkCounter_++;

    // Report performance
    if (chunkCounter_%reportInterval == 0)
    {
        const double B2MiB = 1.0/(1024.0*1024.0);
        int elapsed = timer_.elapsed();
        size_t dataReceived = packetSize * reportInterval;
        size_t maxBufferSize_ = maxBufferSize();
        size_t allocatedSize_ = allocatedSize();
        size_t usedSize_ = usedSize();
        size_t usableSize_ = usableSize(packetSize);
        // Buffer % full (how much of the buffer is in use as a %)
        double pBufferFull = ((maxBufferSize_-usableSize_)/(double)maxBufferSize_)*100.0;
        char prefix[10];
        int l = (reportCounter_ < 10) ? 2 : ((reportCounter_ < 100) ? 1 : 0);
        sprintf(prefix, "S[%s%llu] ", string(l, '-').c_str(), reportCounter_);
        printf("%s\n", string(80,'*').c_str());
        printf("%sTotal chunk count    = %llu\n", prefix, chunkCounter_);
        printf("%sChunk size           = %-7.3f MiB [%i B]\n", prefix,
                packetSize*B2MiB, packetSize);
        printf("%sTotal data received  = %.1f MiB\n", prefix,
                (quint64)packetSize*chunkCounter_*B2MiB);
        printf("%s\n", prefix);
        printf("%sBuffer state:\n", prefix);
        printf("%s* Percent full       = %.1f%%\n", prefix, pBufferFull);
        printf("%s* Total size         = %-7.3f MiB [%lu B]\n", prefix,
                maxBufferSize_*B2MiB, maxBufferSize_);
        printf("%s* Allocated size     = %-7.3f MiB [%lu B]\n", prefix,
                allocatedSize_*B2MiB, allocatedSize_);
        printf("%s* In use (active)    = %-7.3f MiB [%lu B]\n", prefix,
                usedSize_*B2MiB, usedSize_);
        printf("%s* Usable space       = %-7.3f MiB [%lu B]\n", prefix,
                usableSize_*B2MiB, usableSize_);
        printf("%s* Total chunks       = %i\n", prefix, numChunks());
        printf("%s* Active chunks      = %i\n", prefix, numActiveChunks());
        printf("%s* Expired chunks     = %i\n", prefix, numExpiredChunks());
        printf("%s* Usable chunks      = %i\n", prefix, numUsableChunks(packetSize));
        printf("%s* Overwritten chunks = %llu\n", prefix, totalOverwriteCounter_);
        printf("%s* Overwritten chunks = %i, %.1f%% (in report interval)\n", prefix,
                intervalOverwriteCounter_,
                (double)intervalOverwriteCounter_/reportInterval*100.0);
        printf("%s\n", prefix);
        printf("%sReport interval:\n", prefix);
        printf("%s* Chunks received    = %i\n", prefix, reportInterval);
        printf("%s* Data received      = %-7.3f MiB [%lu B] \n", prefix,
                dataReceived*B2MiB, dataReceived);
        printf("%s* Time taken         = %.3f s\n", prefix, elapsed*1.0e-3);
        printf("%s* Data rate          = ", prefix);
        if (elapsed > 0)
            printf("%-7.3f MiB/s\n", dataReceived*B2MiB/(elapsed*1.0e-3));
        else
            printf("---     MiB/s\n");
        printf("%s\n\n", string(80,'*').c_str());
        fflush(stdout);
        reportCounter_++;
        intervalOverwriteCounter_ = 0;
        timer_.restart();
    }
}
/*
 * The routeTcpMessage() receives messages from any TCP connection. The Daemon can be connected with server and deskApp at the same time, but it will know which connection received data.
 * Any message arrive by TCP must to have two parts. The first part defines the data size of the coming package (second part) and must to be an 8 bytes String (always 8 bytes).
 *
 * The algoritm works like this:
 * When some data arrive it verifies (using the hasPackage variable) if is the first part or the second one of the complete message;
 * If hasPackage is true then is especting the second part of the message, otherwise the dada just arrived is the size information.
 *
 * The information of size correspond to the size of the message package. So, when more data arrive it verifies if the size is greater than or equals to the expected size.
 * If true the message is all here and can go on, otherwise the message is coming and it will wait for more data.
 *
 * When all the message arrives it will interpret and route it (by message type) to the right way.
 *
 */
void RFIDMonitorDaemon::routeTcpMessage()
{
    QTcpSocket *connection = (QTcpSocket *) QObject::sender();

    static bool hasPackage = false;
    static quint64 packageSize = 0;

    if( ! hasPackage){

        if((quint64)connection->bytesAvailable() < sizeof(quint64))
            return;

        //    	m_tcpSocket->read((char *)&packageSize, sizeof(quint64));
        QString packageSizeStr(connection->read(sizeof(quint64)));
        packageSize = packageSizeStr.toULongLong();

        qDebug() <<  QString("Message = %1 - Size of coming package: %2").arg(packageSizeStr).arg(QString::number(packageSize));
        hasPackage = true;
    }

    if((quint64)connection->bytesAvailable() >=  packageSize){
        QByteArray data(connection->read(packageSize));

        json::NodeJSMessage nodeMessage;

        nodeMessage.read(QJsonDocument::fromJson(data).object());
        QString messageType(nodeMessage.type());

        qDebug() << QString("New Message Received: %1").arg(QString(data));


        if(messageType == "SYN-ALIVE"){

            tcpSendMessage(connection, buildMessage(m_configManager->identification(), "ACK-ALIVE").toJson());
            qDebug() << QString("New Message Received: %1").arg(messageType);
        }
        else if (messageType == "ACK-SYN") {

            QJsonObject obj(nodeMessage.jsonData());
            if(!obj.isEmpty()){
                m_configManager->setIdentification(obj);
            }

            bool statusDateTime = m_configManager->setDateTime(nodeMessage.dateTime());
            QJsonObject response = m_configManager->identification();
            response["success"] = QJsonValue(statusDateTime);

            tcpSendMessage(connection, buildMessage(response, "ACK").toJson());

            // Informe RFIDMonitor that server is now connected. Wait 2 seconds;
            if(connection->objectName() == "server"){
                isConnected = true;
                QTimer *timer = new QTimer();
                timer->setSingleShot(true);
                timer->setInterval(2000);
                connect(timer, &QTimer::timeout, [=](){
                    ipcSendMessage(buildMessage(QJsonObject(), "SYNC").toJson());
                    timer->deleteLater();
                });
                timer->start();
            }
        }else if (messageType == "GET-CONFIG") {
            tcpSendMessage(connection, buildMessage(m_configManager->currentConfig(), "CONFIG").toJson());

        }else if (messageType == "READER-COMMAND") {

            QJsonObject command(nodeMessage.jsonData());
            /*
             * When a 'reader command' message is received is because someone is sending a command to the reader. So it needs to send also who is doing this.
             * To perform this it uses a field called 'sender' that carry the name of who is sending the 'command message'.
             * And based on that, it will respond to the server connection or to the deskApp connection
             *
             * see reoutIcpMessage (messageType == "READER-RESPONSE")
             */
            if(connection->objectName() == "server")
                command.insert("sender", QString("server"));
            else
                command.insert("sender", QString("app"));

            ipcSendMessage(buildMessage(command, "READER-COMMAND").toJson());

        }else if (messageType == "NEW-CONFIG") {

            QJsonObject newConfig(nodeMessage.jsonData());
            bool ackConf;
            if(m_configManager->newConfig(newConfig))
            {
                // Send a message to stop the RFIDMonitor
                emit restartMonitor();
                ackConf = true;
            }else{
                ackConf = false;
            }
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(ackConf));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NEW-CONFIG").toJson());

            if(m_tcpAppSocket->isOpen())
                m_tcpAppSocket->close();

        }else if (messageType == "DATETIME") {

            QJsonObject dataObj;
            dataObj["success"] =  QJsonValue(m_configManager->setDateTime(nodeMessage.dateTime()));
            tcpSendMessage(connection, buildMessage(dataObj, "ACK").toJson());

        }else if (messageType == "ACK-DATA") {
            // A ACK-DATA message means that the server is trying to inform the RFIDMonitor that some data is now synced. So, it just send this message to the RFIDMonitor.
            ipcSendMessage(data);

        }else if (messageType == "GET-NET-CONFIG") {
            // Only return the network configuration.
            tcpSendMessage(connection, buildMessage(m_configManager->netConfig(), "NET-CONFIG").toJson());

        }else if (messageType == "NEW-NET") {

            QJsonObject network = nodeMessage.jsonData();
            // Receive a new configuration for the network (ssid and password).
            QJsonObject dataObj;
            dataObj.insert("success", QJsonValue(m_configManager->setNetConfig(network)));

            // returns a message ACK-NET to inform the sender that the new configuration was set
            tcpSendMessage(connection, buildMessage(dataObj, "ACK-NET").toJson());

            // Try to restar the network service to already use the new configuration
            bool resetNet = m_configManager->restartNetwork();
            qDebug() <<  QString(resetNet? "Network restarted" : "Networkt Don't restarted");

        }else if (messageType == "ACK-UNKNOWN") {
            QJsonDocument unknown(nodeMessage.jsonData());
            QJsonObject oldMessage(unknown.object().value("unknownmessage").toObject());
            qDebug() <<  "The server don't understand the message type: " << oldMessage.value("type").toString();
            qDebug() <<  "ERROR message: " << unknown.object().value("errorinfo").toString();

        }else if (messageType == "FULL-READ"){
            ipcSendMessage(data);

        }else{
            /* When receives a message that can't be interpreted like any type is an unknown message.
             * In this case an ACK-UNKNOWN message is built and sent to the connection that received this message
             */
            qDebug() <<  "UNKNOWN MESSAGE";
            QJsonObject unknownObj;
            unknownObj.insert("unknownmessage", QJsonValue(QJsonDocument::fromJson(data).object()));
            unknownObj.insert("errorinfo", QString("Unknown message received"));
            tcpSendMessage(connection, buildMessage(unknownObj, "ACK-UNKNOWN").toJson());
        }

        /* when all the process is done, reset the expecting message size to zero and the haspackage to false.
         * Then when more data arrive it must to be the size information again.
         */
        packageSize = 0;
        hasPackage = false;
    }
}
void getEclipseProperty(Matrix& propertyFrames, const QString &hostName, quint16 port, QString caseName, QString propertyName)
{
    QString serverName = hostName;
    quint16 serverPort = port;

    const int Timeout = 5 * 1000;

    QTcpSocket socket;
    socket.connectToHost(serverName, serverPort);

    if (!socket.waitForConnected(Timeout))
    {
        error((("Connection: ") + socket.errorString()).toLatin1().data());
        return;
    }

    // Create command and send it:

    QString command("GetProperty ");
    command += caseName + " " + propertyName;
    QByteArray cmdBytes = command.toLatin1();

    QDataStream socketStream(&socket);
    socketStream.setVersion(QDataStream::Qt_4_0);

    socketStream << (qint64)(cmdBytes.size());
    socket.write(cmdBytes);

    // Get response. First wait for the header

    while (socket.bytesAvailable() < (int)(2*sizeof(quint64)))
    {
        if (!socket.waitForReadyRead(Timeout))
        {
            error((("Wating for header: ") + socket.errorString()).toLatin1().data());
            return;
        }
    }

    // Read timestep count and blocksize

    quint64 timestepCount;
    quint64 byteCount;
    size_t  activeCellCount;

    socketStream >> timestepCount;
    socketStream >> byteCount;

    activeCellCount = byteCount / sizeof(double);
    propertyFrames.resize(activeCellCount, timestepCount);

    if (!(byteCount && timestepCount))
    {
        error ("Could not find the requested data in ResInsight");
        return;
    }

    // Wait for available data for each timestep, then read data for each timestep
    for (size_t tIdx = 0; tIdx < timestepCount; ++tIdx)
    {
        while (socket.bytesAvailable() < (int)byteCount)
        {
            if (!socket.waitForReadyRead(Timeout))
            {
                error((("Waiting for timestep data number: ") + QString::number(tIdx)+  ": " + socket.errorString()).toLatin1().data());
                octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
                return ;
            }
           OCTAVE_QUIT;
        }

        qint64 bytesRead = 0;
        double * internalMatrixData = propertyFrames.fortran_vec();

#if 1 // Use raw data transfer. Faster.
        bytesRead = socket.read((char*)(internalMatrixData + tIdx * activeCellCount), byteCount);
#else
        for (size_t cIdx = 0; cIdx < activeCellCount; ++cIdx)
        {
            socketStream >> internalMatrixData[tIdx * activeCellCount + cIdx];

            if (socketStream.status() == QDataStream::Ok) bytesRead += sizeof(double);
        }
#endif

        if ((int)byteCount != bytesRead)
        {
            error("Could not read binary double data properly from socket");
            octave_stdout << "Active cells: " << activeCellCount << ", Timesteps: " << timestepCount << std::endl;
        }

        OCTAVE_QUIT;
    }

    QString tmp = QString("riGetActiveCellProperty : Read %1").arg(propertyName);

    if (caseName.isEmpty())
    {
        tmp += QString(" from active case.");
    }
    else
    {
        tmp += QString(" from %1.").arg(caseName);
    }
    octave_stdout << tmp.toStdString() << " Active cells : " << activeCellCount << ", Timesteps : " << timestepCount << std::endl;

    return;
}