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 #2
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 #3
0
void FenServeur::donneesRecues()
{
    // 1 : on reçoit un paquet (ou un sous-paquet) d'un des clients
    // On détermine quel client envoie le message (recherche du QTcpSocket du client)
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0) // Si par hasard on n'a pas trouvé le client à l'origine du signal, on arrête la méthode
        return;

    // Si tout va bien, on continue : on récupère le message

    QDataStream in(socket);

    if (tailleMessage == 0) // Si on ne connaît pas encore la taille du message, on essaie de la récupérer
    {
        if (socket->bytesAvailable() < (int)sizeof(quint16)) // On n'a pas reçu la taille du message en entier
             return;

        in >> tailleMessage; // Si on a reçu la taille du message en entier, on la récupère
    }

    // Si on connaît la taille du message, on vérifie si on a reçu le message en entier
    if (socket->bytesAvailable() < tailleMessage) // Si on n'a pas encore tout reçu, on arrête la méthode
        return;

    // Si ces lignes s'exécutent, c'est qu'on a reçu tout le message : on peut le récupérer !
    QString message;
    in >> message;

    // 2 : on renvoie le message à tous les clients
    envoyerATous(message);

    // 3 : remise de la taille du message à 0 pour permettre la réception des futurs messages
    tailleMessage = 0;
}
Example #4
0
void my_server::slotReadClient()
{

    QTcpSocket* pClientSocket = (QTcpSocket*)sender();
    QDataStream in(pClientSocket);
    //in.setVersion(QDataStream::Qt_4_2);
    for (;;) {
        if (!m_nNextBlockSize) {
            if (pClientSocket->bytesAvailable() < sizeof(quint16)) {
                break;
            }
            in >> m_nNextBlockSize;
        }

        if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
            break;
        }
        QTime   time;
        QString str;
        in >> time >> str;

        QString strMessage =
            time.toString() + " " + "Client has sended - " + str;
        emit text_to_console(strMessage);
        qDebug() << strMessage;

        m_nNextBlockSize = 0;
    }
}
Example #5
0
//получаем сообщения от клиента
void InformerTCPServer::slotReadClient()
{
    QTcpSocket *pClientSocket = (QTcpSocket*)sender();
    QDataStream in(pClientSocket);
    in.setVersion(QDataStream::Qt_4_8);
    for(;;){
        if(!m_nNextBlockSize){
            if(pClientSocket->bytesAvailable() < sizeof(quint16))
                break;
        }
        in >> m_nNextBlockSize;

        if (pClientSocket->bytesAvailable() < m_nNextBlockSize) {
            break;
        }
        QTime time;
        QString str;
        in >> time >> str; //записываем сообщения от клиента
        //time записываем себе в лог, например
        //str пишем туда же
        m_nNextBlockSize = 0; //обнуляем счетчик байт

        sendToClient(pClientSocket, trUtf8("Сервак ответил")/*отправить сообщение клиенту "бла-бла-бла"*/);
    }
}
void fenetre_bc::donneesRecues()
{
    // On détermine quel client envoie le message (recherche du QTcpSocket du client)
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0) // Si on n'a pas trouvé le client à l'origine du signal, on return
        return;

    // Si non on récupère le message
    QDataStream in(socket);

    if (tailleMessage == 0) // on recupere la taille du message
    {
        if (socket->bytesAvailable() < (int)sizeof(quint16))
             return;

        in >> tailleMessage;
    }

    // Si on connaît la taille du message, on vérifie si on a reçu le message en entier
    if (socket->bytesAvailable() < tailleMessage) // Si on n'a pas encore tout reçu, on arrête la méthode
        return;


    // on a reçu tout le message : on le recupere
    in >>contenu_frame;

    liste_BC->append(contenu_frame);
    liste_BC->update();

    message_is_recieved=true;  // on indique qu'un message a été recu

    //  remise de la taille du message à 0 pour permettre la réception des futurs messages
    tailleMessage = 0;
}
Example #7
0
void CameraTcpServer::readReceivedData()
{
	QTcpSocket * client = (QTcpSocket*)sender();
	QDataStream in(client);
	in.setVersion(QDataStream::Qt_4_0);

	if (blockSize_ == 0)
	{
		if (client->bytesAvailable() < (int)sizeof(quint64))
		{
			return;
		}

		in >> blockSize_;
	}

	if (client->bytesAvailable() < (int)blockSize_)
	{
		return;
	}

	std::vector<unsigned char> buf(blockSize_);
	in.readRawData((char*)buf.data(), blockSize_);
	images_.push_back(cv::imdecode(buf, cv::IMREAD_UNCHANGED));
	int queue = Settings::getCamera_9queueSize();
	while(queue > 0 && images_.size() > queue)
	{
		images_.pop_front();
	}
	blockSize_ = 0;
}
Example #8
0
void Server::slotReadClient()
{
	QTcpSocket* pClientSocket = (QTcpSocket*)sender();
	QDataStream in(pClientSocket);
	//in.setVersion(QDataStream::Qt_4_8);
	for(;;)
	{
		if (!NextBlockSize)
		{
			if (pClientSocket->bytesAvailable() < sizeof(quint16)) break;
			in >> NextBlockSize;
		}
		if (pClientSocket->bytesAvailable() < NextBlockSize) break;
		QTime time;
		QString str;
		in >> time >> str;
		QString strMessage = time.toString() + " " + "Client has sent - " + str;
		//ptxt->append(strMessage);
		emit signal_display(strMessage);
		NextBlockSize = 0;
		str = "Server Response: Recived " + str + "/";
		QString *pstr = &str;
		sendToClient(pClientSocket, *pstr);
	}
}
Example #9
0
//SLOT : quand un message arrive, le récupère et le traite
void Server::receiveMessage()
{

    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;

    QDataStream in(socket);

    while(1) {

        if (tailleMessage == 0) {
            if (socket->bytesAvailable() < (int)sizeof(tailleMessage))
                return;

            in >> tailleMessage;
        }

        if (socket->bytesAvailable() < tailleMessage)
            return;

        //récupère le message
        QString messageRecu;
        in >> messageRecu;


        qDebug() <<"Received message: " << messageRecu;
        processRequest(messageRecu,socket);

        // reset for the next message
        tailleMessage = 0;
    }
}
Example #10
0
void ServerModel::Read()
{
    QTime time;
    QString str, message;

    QTcpSocket* socket = qobject_cast<QTcpSocket *>(sender());
    QDataStream in(socket);

    while(true)
    {
        if(!m_nextBlockSize)
        {
            if(socket->bytesAvailable() < sizeof(quint16))
                break;
			in >> m_nextBlockSize;
        }

        if(socket->bytesAvailable() < m_nextBlockSize)
            break;

        in >> time >> str;

		message = time.toString() + " " + "Client has sent - " + str;
		emit SendMessageToMainForm(message);
		m_nextBlockSize = 0;
    }
}
Example #11
0
void CGalconServer::slotReadClient()
{
   QTcpSocket* pClientSocket = (QTcpSocket*)sender();
   QDataStream in(pClientSocket);
   in.setVersion(QDataStream::Qt_4_7);
   qint16 nextBlockSize = 0;
   for (;;)
   {
      if (pClientSocket->bytesAvailable() < sizeof(quint16))
      {
         break;
      }
      in >> nextBlockSize;

      if (pClientSocket->bytesAvailable() < nextBlockSize)
      {
         break;
      }

      QByteArray str;
      in >> str;

      ui->tEClient->append(QString(str));

      nextBlockSize = 0;
   }
}
Example #12
0
void Graph::onReadyRead()
{
	qDebug() << "Graph::readPriborData()";
	QTcpSocket *socket = (QTcpSocket *)sender();
	const size_t header_size = sizeof(ident_t) + sizeof(int);
	while(socket->bytesAvailable() >= header_size)
	{
		char buf[header_size];
		socket->peek(buf, sizeof(buf));
		ident_t id = *reinterpret_cast<ident_t *>(buf);
		int nvals = *(int *)((ident_t *)buf + 1);
		qDebug() << " " << id << nvals << socket->bytesAvailable();
		if(socket->bytesAvailable() < nvals*sizeof(Value) + sizeof(id) + sizeof(nvals)) break;
		socket->read((char *)&id, sizeof(id));
		socket->read((char *)&nvals, sizeof(nvals));
		QByteArray data = socket->read(nvals*sizeof(Value));
		if((size_t)data.size() < nvals*sizeof(Value)) break;
		const Value *v = (const Value *)data.constData();
		QVector<Value> vals(nvals);
		qCopy(v, v + nvals, vals.begin());
		for(Stats::iterator s = stats.begin(); s != stats.end(); ++s)
		{
			Sourcer *sourcer = s.key();
			if(sourcer->ident() == id)
			{
				if(sourcer->getReliability() == 1)
					vals.append(Value(QDateTime::currentDateTime().toTime_t(), sourcer->value()));
				s->resize(w, Stat());
				fillStats(*s, currentInterval(), vals);
				update();
			}
		}
	}
}
Example #13
0
void Server::recieveData()
{
    QMap<quint32, QTcpSocket *>::const_iterator i = sockets->constBegin();

    while (i != sockets->constEnd()) {
        QTcpSocket* tcpSocket = i.value();
        if (tcpSocket && tcpSocket->bytesAvailable()>0) {
            int size = tcpSocket->bytesAvailable();
            QDataStream in(tcpSocket);
            in.setVersion(QDataStream::Qt_4_0);
            char *mem = new char[size];
            in.readRawData(mem, size);
            QString message = QString::fromUtf8(mem, size).trimmed();
            delete mem;
            emit write_message(tr("Recieved data (size=%1) from %2. Content: \"%3\"").arg(size).arg(tcpSocket->peerAddress().toString()).arg(message));

            if (message.startsWith("POST /sms HTTP/")) {
                processEventGroup("sms", message, tcpSocket);
            } else if (message.startsWith("POST /smsread HTTP/")) {
                processEventGroup("smsread", message, tcpSocket);
            } else if (message.startsWith("POST /phone HTTP/")) {
                processEventGroup("phone", message, tcpSocket);
            } else if (message.startsWith("POST /phoneread HTTP/")) {
                processEventGroup("phoneread", message, tcpSocket);
            } else if (message.startsWith("POST /notify HTTP/")) {
                processEventGroup("notify", message, tcpSocket);
            } else  {
                processMessageGroup(message, i.key());
            }
        }
        ++i;
    }
}
Example #14
0
// ----------------------------------------------------------------------
void MyServer::slotReadClient()
{
    QTcpSocket* pClientSocket = (QTcpSocket*)sender();

    QDataStream in(pClientSocket);

    in.setVersion(QDataStream::Qt_4_7);

// в цикле проверяем - а все ли данные нам уже пришли? Как только удостоверяемся,что все - продолжаем
    for (;;) {
        if (!m_nNextBlockSize)
          {
            if (pClientSocket->bytesAvailable() < (int)sizeof(quint16))
              {
                break;
              }
            in >> m_nNextBlockSize;
          }

        if (pClientSocket->bytesAvailable() < m_nNextBlockSize)
          {
            break;
          }

        QTime time = QTime::currentTime();

        Sender_socket* pcSocket;

//смотрим, а какой из клиентов отправил нам данные
        for (int j = 0; j < 4;j++)
            if (clients[j].my_client == pClientSocket)
            {
                pcSocket = &clients[j];
                break;
            }

         pcSocket->message = new int[32];

         qDebug() <<"Message: ";

//записываем полученные данные
         for(int j = 0 ; j < 32;j++)
         {
             in >>pcSocket->message[j];
             qDebug()<< pcSocket->message[j]<< " ";

         }


        QString strMessage =
            time.toString() + " " + "Client has sent message.";

        m_ptxt->append(strMessage);


        m_nNextBlockSize = 0;


    }
}
Example #15
0
void CTcpServer::clientHasData(QObject *obj)
{
    qDebug() << "Received client data\n";

    QTcpSocket *socket = qobject_cast<QTcpSocket *>(obj);
    emit dataReceived(socket->readAll());

#if 0
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_4);

    while (true)
    {
        if (clientInfo[socket] == 0)
        {
            if (socket->bytesAvailable() < (int)sizeof(quint32))
                return;

            in >> clientInfo[socket];
        }

        if (socket->bytesAvailable() < clientInfo[socket])
            return;

        clientTcpReceived(in);
        clientInfo[socket] = 0;
    }
#endif
}
void MessageDispatcherThread::run()
{
    QTcpSocket socket;
    socket.setSocketDescriptor(m_descriptor);
    quint64 dataSize = 0;

    while(!m_doQuit)
    {
        socket.waitForReadyRead();

        if (dataSize == 0) {
            QDataStream stream(&socket);
            stream.setVersion(QDataStream::Qt_4_6);

            if (socket.bytesAvailable() < sizeof(quint64))
                continue;

            stream >> dataSize;
        }

        if (socket.bytesAvailable() < dataSize)
            continue;

        emit gotMessage(socket.readAll(), socket.peerAddress());
        break;
    }
Example #17
0
void Server::slotReadClient()
{
    QTcpSocket* pClientSocket = (QTcpSocket*)sender();

    QDataStream data(pClientSocket);
    data.setVersion(QDataStream::Qt_5_4);

    QString buf;
    qint16 nextBlockSize = 0;

    for(;;)
    {
        if(!nextBlockSize)
        {
            if(pClientSocket->bytesAvailable() < sizeof(qint16))
                break;

            data >> nextBlockSize;
        }
        if(pClientSocket->bytesAvailable() < nextBlockSize)
            break;

        data >> buf;
        if(!buf.isEmpty())
            sendToClient(pClientSocket, scanner.scanFile(buf));

        nextBlockSize = 0;
    }
}
Example #18
0
void Server::recieveData()
{
    QTcpSocket* tcpSocket = remote_server_socket;
    if (tcpSocket && tcpSocket->bytesAvailable()>0) {
        int size = tcpSocket->bytesAvailable();
        QDataStream in(tcpSocket);
        in.setVersion(QDataStream::Qt_4_0);
        char *mem = new char[size];
        in.readRawData(mem, size);
        QString message = QString::fromUtf8(mem, size);
        delete mem;
        emit write_message(tr("Recieved data (size=%1) from %2. Content: \"%3\"").arg(size).arg(tcpSocket->peerAddress().toString()).arg(message));
        if (!is_config_mode) {
            QHash<QString, ClientAction *>::const_iterator i = actions->constBegin();
            while (i != actions->constEnd()) {
                if (i.value() && i.value()->isEnabled() && !i.value()->getPrefix().isEmpty() && message.startsWith(i.value()->getPrefix()+"=")) {
                    QString params_message = message;
                    params_message.replace(QRegExp("^("+i.value()->getPrefix()+")\\="), "");
                    i.value()->setParamsFromMessage(params_message);
                    i.value()->runAction();
                }
                ++i;
            }
        } else if(message.startsWith("DS_SETUP:\r\n")) {
            QStringList params_message = message.split("\r\n");
            params_message.removeFirst();
            if (!params_message.isEmpty() && params_message.length()>=4) {
                device_id = params_message.value(3, "0").toInt();
                remoteIPAddress = params_message.value(2, "");
                emit set_config(remoteIPAddress, device_id);
            }
        }
    }
}
Example #19
0
void MonServeur::dataIncoming()
{
	QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());

	if (socket == 0)
		return;

	QDataStream in(socket);

	if (_sizeMessage == 0)
	{
		if (socket->bytesAvailable() < (int)sizeof(quint16))
			return;

		in >> _sizeMessage;
	}

	if (socket->bytesAvailable() < _sizeMessage)
		return;

	QString message;
	in >> message;

	sendAll(message);

	_sizeMessage = 0;
}
Example #20
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 #21
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 #22
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;
}
Example #23
0
//----------------------------------------------------------------------------------
void tst_QTcpServer::ipv4PerformanceTest()
{
    QTcpSocket probeSocket;
    probeSocket.connectToHost(QtNetworkSettings::serverName(), 143);
    QVERIFY(probeSocket.waitForConnected(5000));

    QTcpServer server;
    QVERIFY(server.listen(probeSocket.localAddress(), 0));

    QTcpSocket clientA;
    clientA.connectToHost(server.serverAddress(), server.serverPort());
    QVERIFY(clientA.waitForConnected(5000));

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

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

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

    delete clientB;
}
Example #24
0
void TCPReceiveRawNode::frameStart( qint64 pTimeStamp )
{
	if( !mStream )
	{
		return;
	}

	QTcpSocket		*S = qobject_cast<QTcpSocket *>( mStream->device() );

	if( !S->isOpen() )
	{
		delete mStream;
		delete S;

		mStream = nullptr;

		return;
	}

	if( !S->bytesAvailable() )
	{
		return;
	}

	fugio::Performance	Perf( mNode, "frameStart", pTimeStamp );

	mValOutputBuffer->setVariant( S->readAll() );

	pinUpdated( mPinOutputBuffer );
}
Example #25
0
void ClientSktTcp::newData()
{
    QTcpSocket* s = qobject_cast<QTcpSocket*>(sender());
    if (!s) return;

    qint64 bufLen = s->bytesAvailable();
    char* buf = TK::createBuffer(bufLen, MAXBUFFER);
    if (!buf) return;

    qint64 readLen = 0;
    qint64 ioLen = s->read(buf, bufLen);

    while (ioLen > 0)
    {
        readLen += ioLen;
        ioLen = s->read(buf+readLen, bufLen-readLen);
    }

    if (ioLen >= 0)
    {
        recordRecv(readLen);
        dump(buf, readLen, false);
    }

    TK::releaseBuffer(buf);
}
Example #26
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;
}
Example #27
0
void Server::readyRead()
{
	QTcpSocket * socket = static_cast<QTcpSocket *>(sender());
	QByteArray * buffer = _buffers.value(socket);
	qint32 size = *_sizes.value(socket);
	while(socket->bytesAvailable() > 0)
	{
		buffer->append(socket->readAll());
		// While can process data, process it
		while ((buffer->count() >= 4 && size == 0) || (buffer->count() >= size && size > 0))
		{
			// If size of data has received completely, then store it on global variable
			if (buffer->count() >= 4 && size == 0)
			{
				size = arrayToInt(buffer->mid(0, 4));
				buffer->remove(0, 4);
			}
			// If data has received completely
			if (buffer->count() >= size && size > 0)
			{
				QByteArray data = buffer->mid(0, size);
				buffer->remove(0, size);
				size = 0;
				processData(data, socket);
			}
		}
	}
}
Example #28
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 #29
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 #30
0
void Server::readyRead()
{
  QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
  QByteArray* buffer = buffers.value(socket);
  qint32* s = sizes.value(socket);
  qint32 size = *s;
  while(socket->bytesAvailable() > 0) {
    buffer->append(socket->readAll());
    while((size == 0 && buffer->size() >= 4) || (size > 0 && buffer->size() >= size))
    {
      if(size == 0 && buffer->size() >= 4)
      {
        size = ArrayToInt(buffer->mid(0, 4));
        *s = size;
        buffer->remove(0, 4);
      }
      if(size > 0 && buffer->size() >= size)
      {
        QByteArray data = buffer->mid(0, size);
        buffer->remove(0, size);
        size = 0;
        *s = size;
        emit dataReceived(socket, data);
      }
    }
  }
}