Beispiel #1
0
Connection* SharedDaemon::createCustomConnection(int listenSocketNum, void *data)
{
    SharedDaemon::ConnectionType typeOfConnection = *((SharedDaemon::ConnectionType*)(data));
    if(typeOfConnection == SharedDaemon::WSocketConnection )
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);

        QTcpSocket * tcpSocket = new QTcpSocket();
        tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
        tcpSocket->waitForReadyRead();

        QString request = QString(tcpSocket->readAll());

        if(request.size() == 0) /// firefox works differently, and sends 0 size messages
        {
            tcpSocket->close();
            tcpSocket->disconnectFromHost();
            tcpSocket->waitForDisconnected();
            tcpSocket->deleteLater();

            descriptor = SingleThreadedAcceptSocket(listenSocketNum);
            tcpSocket = new QTcpSocket();
            tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState );
            tcpSocket->waitForReadyRead();
            request = QString(tcpSocket->readAll());
        }

        return new WebSocketConnection(tcpSocket,request);
    }
    else
    {
        int descriptor = SingleThreadedAcceptSocket(listenSocketNum);
        return new SocketConnection(descriptor);
    }
}
Beispiel #2
0
void HTTPServer::slt_ConnectionHandler()
{
    qDebug() << "[HTTPServer:]\tHave a new connection\n";
    QTcpSocket * socket = server.nextPendingConnection();
    socket->waitForReadyRead();
    QByteArray request(socket->readAll());
    QStringList buf = QString(request).split(' ');

    qDebug() << "Data received:\t" << buf.at(0);

    if(buf.at(0) == "POST")
    {
        QString responce = "HTTP/1.1 200 OK\r\n\r\n%1";
        socket->waitForReadyRead();
        QByteArray data(socket->readAll());
        socket->write(responce.toLatin1());
        socket->waitForBytesWritten();
        socket->disconnectFromHost();
        socket->deleteLater();

        qDebug() << "Data received: " << data;
        //--------
        //QJsonDocument doc = QJsonDocument::fromJson(data);
        //parse(doc);
    }
}
Beispiel #3
0
void ServerSwitcher::run() 
{
	QString tmp ;
	QUrl url(this->mServer + this->mRequest) ;
	QTcpSocket sock ;
	sock.connectToHost(url.host(),url.port(80));
	
	if( sock.waitForConnected() )
	{
		tmp = "GET /nowgo/%1 HTTP/1.0\r\n"
			"Host: %2\r\n"
			"User-Agent: NullGet\r\n"
			"Connection: close\r\n"
			"\r\n";
		tmp = tmp.arg(this->mRequest).arg(url.host());
		sock.write(tmp.toLatin1());
		if( sock.waitForBytesWritten() )
		{
			QByteArray ball ;
			while( sock.waitForReadyRead() )
			{
				if( ball.isEmpty())
					ball = sock.readAll();
				else
					ball += sock.readAll();
			}
			qDebug()<< ball ;
		}
	}
}
void FetchThread::process(QString phost)
{

    QUdpSocket *udpSocket ;
    udpSocket= new QUdpSocket(0);
    udpSocket->bind(QHostAddress::LocalHost, 9999);
    udpSocket->waitForConnected(250);



    QTcpSocket socket;
    socket.connectToHost("localhost", 4949);
    socket.waitForConnected(500);

    while (socket.waitForReadyRead(250));
    QString t_hello = socket.readAll();
    qDebug() << "READ: " << t_hello;

    socket.write(QString("list\n").toStdString().c_str() );
    while (socket.waitForReadyRead(250));
    QString buf1 = socket.readAll();

    qDebug() << "READ: " << buf1;
    QStringList list_probe = buf1.split(QRegExp("\\s+"));

    for (int z=0; z< list_probe.size(); z++)
    {
        QString probe=list_probe.at(z);
        QString cmd = QString("fetch ").append(probe).append("\n");
        qDebug() << "cmd : " << cmd;
        socket.write(cmd.toStdString().c_str() );


        while (socket.waitForReadyRead(250));
        QString buf2 = socket.readAll();
        qDebug() << "Rep fetch :" << buf2 << "\n";

        QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n");
        QRegularExpressionMatchIterator i = re.globalMatch(buf2);
        re.setPatternOptions(QRegularExpression::MultilineOption);

        while (i.hasNext()) {
            QRegularExpressionMatch match = i.next();
            QString s_metric = match.captured(1);
            QString s_value = match.captured(3);
            QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch());
            qDebug() << "metric:  " << s_mtr.toLower();

            udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999);




        }

        udpSocket->close();


    }
}
Beispiel #5
0
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();
    }
}
Beispiel #6
0
void MyHttpServer::slotNewConnectionHandler()
{
    qDebug() << " [ ]Have a new connection!";
    QTcpSocket* sock = m_pServer.nextPendingConnection();
    sock->waitForReadyRead();
    QByteArray request(sock->readAll());
    qDebug() << request;
    QStringList buf = QString(request).split(' ');

    if(buf.at(0) == "GET")
    {
        QString responce = "HTTP/1.1 200 OK\r\n\r\n%1";
        sock->write(responce.arg(QTime::currentTime().toString()).toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();
        return;
    }

    if(buf.at(0) == "POST")
    {
	QString destUrl(buf.at(1));
        sock->waitForReadyRead();
        QByteArray data(sock->readAll());
        qDebug() << "put " << QString(data) << " into " << destUrl;
        QString responce = "HTTP/1.1 200 OK\r\n\r\n";
        sock->write(responce.toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();

        //QByteArray payload;
        //payload.append(QString(data).split('=').at(1));
        //payload = QByteArray::fromBase64(QByteArray::fromPercentEncoding(payload));
        //qDebug() << payload;

        //QJsonDocument doc = QJsonDocument::fromJson(payload);
        //QJsonObject jObj = doc.object();
        //QString table = destUrl.split('/').at(2);
        //qDebug() << "table: " << table << " object: " << jObj;


        return;
    }

//    connect(sock, SIGNAL(readyRead()), this, SLOT(slotReadDataHandler()));
//    connect(sock, SIGNAL(disconnected()), this, SLOT(slotDisconnectedHandler()));
}
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 );
}
void ListenRISRequests::newRISRequest()
{
    QTcpSocket *tcpSocket = m_tcpRISServer->nextPendingConnection();
    QString risRequestData;

    INFO_LOG("Rebuda peticio de la IP " + tcpSocket->peerAddress().toString());
    if (tcpSocket->waitForReadyRead(TimeOutToReadData))
    {
        risRequestData = QString(tcpSocket->readAll());
        INFO_LOG("Dades rebudes: " + risRequestData);
    }
    else
    {
        INFO_LOG("No s'ha rebut dades, error: " + tcpSocket->errorString());
    }

    INFO_LOG("Tanco socket");
    tcpSocket->disconnectFromHost();
    INFO_LOG("Faig delete del socket");
    delete tcpSocket;

    if (!risRequestData.isEmpty())
    {
        processRequest(risRequestData);
    }
}
Beispiel #9
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
}
Beispiel #10
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);
      }
    }
  }
}
Beispiel #11
0
void ServerCore::processDeviceCommandSocket()
{
	if (!serverStart)
	{
		return;
	}

	QTcpSocket *socket = deviceCmdServer->nextPendingConnection();

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		QVariantMap retParamMap = prepareDataForDevice(jsonObj);
		TCP_REPLY_TYPE retType = (TCP_REPLY_TYPE)retParamMap[JSON_KEY_RETURN_TYPE].toInt();

		QString retString = JsonGenerator::GenerateJsonReply(retType, retParamMap);
		QString peerAddress = socket->peerAddress().toString();
		socket->write(retString.toLatin1());

		bool isSuccess = socket->waitForBytesWritten();

		Q_EMIT dataWrittenToDevice(peerAddress, retString);

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});
}
Beispiel #12
0
void WakeServer::slotReadClient()
{
    QTcpSocket* clientSocket = (QTcpSocket*)sender();
    int idusersocs=clientSocket->socketDescriptor();
    wproto->getpacket(clientSocket->readAll());
//    QTextStream os(clientSocket);
//    os.setAutoDetectUnicode(true);
//    os << "HTTP/1.0 200 Ok\r\n"
//          "Content-Type: text/html; charset=\"utf-8\"\r\n"
//          "\r\n"
//          "<h1>WakeServer</h1>\n"
//       << QDateTime::currentDateTime().toString() << "\n";
//    qDebug() << "ReadClient:"+clientSocket->readAll()+"\n\r";
//    // Если нужно закрыть сокет
    clientSocket->close();
    SClients.remove(idusersocs);
    //    while(tcpSocket->canReadLine())
    //    {
    //        QByteArray ba = tcpSocket->readLine();
    //        if(strcmp(ba.constData(), "!exit\r\n") == 0)
    //        {
    //            tcpSocket->disconnectFromHost();
    //            break;
    //        } else {

    //        }
    //        qDebug() << ">> " << ba.constData();
    //    }
}
Beispiel #13
0
void ServerCore::queryDeviceDisplayInfo(QString deviceUID)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT displayInfoRecieved(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QVariantMap paramMap;
	paramMap.insert(JSON_KEY_SEQ, 1234);

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_DISPLAY_INFO, paramMap);

	socket->write(jsonCmd.toLatin1());
}
/**
 * リクエストを転送する
 */
void YASWebProxy::forwardRequest()
{
    QTcpSocket* socket = qobject_cast<QTcpSocket*>(sender());
    QTcpSocket* proxySocket = socket->findChild<QTcpSocket*>("tunnel");
    QByteArray req = socket->readAll();
    proxySocket->write(req);
}
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;
    }
Beispiel #16
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);
			}
		}
	}
}
Beispiel #17
0
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;
}
void server::write(QString value)
{
    QTcpSocket *client = Server->nextPendingConnection();

    if (client->waitForConnected(3000))
    {
        qDebug() << "Client Connected: ...";

        client->write("The connection is sucessfull");

        client->waitForBytesWritten(1000);
        client->waitForReadyRead(3000);

        qDebug() << "Reading" << client->bytesAvailable();

        qDebug() << client->readAll();

        client->close();
    }

    else
    {
        qDebug() << "Connection Failed...";
    }
}
Beispiel #19
0
void ServerCore::sendCommandToDevice(QString deviceUID, QVariantMap paramMap)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT commandReturned(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::SEND_COMMAND_TO_DEVICE, paramMap);

	socket->write(jsonCmd.toLatin1());

	socket->waitForBytesWritten();
	socket->waitForReadyRead();
}
Beispiel #20
0
void
FirehoseModel::onData()
{
    QTcpSocket* r = (QTcpSocket*)sender();
    QByteArray data = r->readAll();
    QDomDocument xml;
    if (!xml.setContent( data )) {
        qWarning() << "Couldn't parse:" << data;
        return;
    }
    
    // I'm mainly lazy because Track.operator== won't work here */
    static QByteArray mxcl_is_lazy; 
    if (data == mxcl_is_lazy)
        return;
    mxcl_is_lazy = data;
    
    try
    {
        WsDomElement e( xml.documentElement() );
        connect( new FirehoseItem( e ), SIGNAL(finished( FirehoseItem* )), SLOT(onItemReady( FirehoseItem* )) );
    }
    catch (std::runtime_error& e)
    {
        qWarning() << e.what();
        qDebug() << data;
    }
}
//return 0: when found IP address
int scan_network::scanIP(QString ip)
{
    QTcpSocket socket;
    QString content = "";

    socket.connectToHost(ip,26001);
    bool flag = socket.waitForConnected();
    if(!flag)
    {
        socket.close();
        socket.deleteLater();

        return 1;
    }

    char *nc_hello = new char [3];
    nc_hello[0]=char(1);
    nc_hello[1]='\t';
    nc_hello[2]='\n';
    socket.write(nc_hello,3);

    delete nc_hello;

    QByteArray ba1;
    content ="";

    socket.waitForReadyRead();
    ba1=socket.readAll();

    while(socket.waitForReadyRead())
        ba1=socket.readAll();

    socket.close();
    socket.deleteLater();

    const char *recv = ba1.constData();
    if (!recv)
        return 1;

    if(strlen(recv)<3)
        return 1;

    if (recv[0]!=char(2) || recv[1]!='\t' || recv[2]!='\n')
        return 1;

    return 0;
}
Beispiel #22
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 tvNetworkControl::sltReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;
    QByteArray recievedData = socket->readAll().toHex();
    emit logText(tr("============ <b>Recieved Datagram</b> =============<br>%1").arg(byteArrayToHexaString(recievedData, false)));
}
Beispiel #24
0
void GroupRequestDlg::slotOkClicked()
{
    if (ui_->rb_allow_->isChecked())
    {
        QString allow_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
                "&msg=&op_type=2&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

        Request req;
        req.create(kGet, allow_url);
        req.addHeaderItem("Host", "d.web2.qq.com");
        req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
        req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
        req.addHeaderItem("Content-Type", "utf-8");

        QTcpSocket fd;
        fd.connectToHost("d.web2.qq.com", 80);
        fd.write(req.toByteArray());

        fd.waitForReadyRead();
        qDebug()<<"allow add group request: "<<fd.readAll();

        accept();
    }
    else
    {
        QString deny_url = "/channel/op_group_join_req?group_uin=" + gid_ + "&req_uin=" + id_ +
                "&msg=" + ui_->le_deny_reason_->text() + "&op_type=3&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

        Request req;
        req.create(kGet, deny_url);
        req.addHeaderItem("Host", "d.web2.qq.com");
        req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
        req.addHeaderItem("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002&callback=2");
        req.addHeaderItem("Content-Type", "utf-8");

        QTcpSocket fd;
        fd.connectToHost("d.web2.qq.com", 80);
        fd.write(req.toByteArray());

        fd.waitForReadyRead();
        qDebug()<<"deny add group request"<<fd.readAll();

        fd.close();
        reject();
    }
}
Beispiel #25
0
void MainWindow::newData()
{
    if(connectedMode=="Tcp socket (QTcpServer)") // if connection is on tcp socket mode
    {
        QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
        int index=-1;
        for (int i = 0; i < tcpSocket.size(); ++i) {
            if(tcpSocket.at(i)->tcpSocket==socket)
                index=i;
        }
        if(index==-1)
        {
            ui->statusBarApp->showMessage("Internal error at newData()",10000);
            return;
        }
        QByteArray block=socket->readAll();
        //load in hexa if needed and append or update the text
        if(ui->comboBoxModeAppend->currentText()=="Update")
            tcpSocket[index]->IncomingData.clear();

        QByteArray raw_data;
        if(ui->compressedStream->isChecked())
            raw_data=tcpSocket[index]->compression->decompressData(block);
        else
            raw_data=block;
        //load in hexa if needed and append or update the text
        tcpSocket[index]->IncomingData.append(raw_data);

        updateCurrentData();
    }
    if(connectedMode==COMBOBOXTEXTLOCALSOCK) // if connection is on local socket mode
    {
        QLocalSocket *socket = qobject_cast<QLocalSocket *>(sender());
        int index=-1;
        for (int i = 0; i < localSocket.size(); ++i) {
            if(localSocket.at(i)->localSocket==socket)
                index=i;
        }
        if(index==-1)
        {
            ui->statusBarApp->showMessage("Internal error at newData()",10000);
            return;
        }
        QByteArray block=socket->readAll();
        //load in hexa if needed and append or update the text
        if(ui->comboBoxModeAppend->currentText()=="Update")
            localSocket[index]->IncomingData.clear();

        QByteArray raw_data;
        if(ui->compressedStream->isChecked())
            raw_data=tcpSocket[index]->compression->decompressData(block);
        else
            raw_data=block;

        localSocket[index]->IncomingData.append(raw_data);
        updateCurrentData();
    }
}
Beispiel #26
0
void TcpClient::readData()
{
    QTcpSocket* myServer = qobject_cast<QTcpSocket*>(sender());
    QByteArray reply = myServer->readAll();

    qDebug() << QString(reply);

    emit ServerReply(QString(reply));
}
Beispiel #27
0
void ServerCore::processNewDevice(QVariantMap& dataMap)
{
	bool isSelfBroadcast = dataMap.contains(JSON_KEY_COMMAND) && dataMap[JSON_KEY_COMMAND] == CMD_QUERY
		&& (!dataMap.contains(JSON_KEY_UID) || !dataMap.contains(JSON_KEY_DISPLAYNAME)
			|| !dataMap.contains(JSON_KEY_IP));

	if (isSelfBroadcast)
	{
		return;
	}

	QString deviceUID = dataMap[JSON_KEY_UID].toString();
	QString deviceName = dataMap[JSON_KEY_DISPLAYNAME].toString();
	QString deviceIP = dataMap[JSON_KEY_IP].toString();
	QString deviceType = dataMap[JSON_KEY_TYPE].toString();

	DeviceInfo devInfo(deviceUID, deviceName, deviceIP, deviceType);
	DeviceManagerModule()->AddDevice(deviceUID, devInfo);

	QVariantMap paramMap;
	paramMap.insert(JSON_KEY_SEQ, 1234);

	QTcpSocket *socket = new QTcpSocket(this);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		parseSupportCmds(deviceUID, byteArray);
		Q_EMIT deviceAdded(deviceUID);
		socket->disconnectFromHost();
	});

	QObject::connect(socket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error),
		[=](QAbstractSocket::SocketError socketError)
	{
		qDebug() << "Socket Error" << socketError;
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	socket->connectToHost(deviceIP, PORT_SERVER_BROADCAST, QIODevice::ReadWrite);

	socket->waitForConnected();

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_SUPPORT_CMDS, paramMap);

	socket->write(jsonCmd.toLatin1());
	socket->flush();

	socket->waitForBytesWritten();
	socket->waitForReadyRead();

	
}
Beispiel #28
0
void ClientTestServer::_incomingFromClient()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>( sender() );
    // record the data sent
    while( socket->bytesAvailable() > 0 )
    {
        _received += socket->readAll();
    }
}
Beispiel #29
0
void IntProcServer::readData()
{
    QObject * object = QObject::sender(); // далее и ниже до цикла идет преобразования "отправителя сигнала" в сокет, дабы извлечь данные
    if (!object)
        return;
    QTcpSocket * socket = static_cast<QTcpSocket *>(object);
    QByteArray arr =  socket->readAll();
    emit messageIn(QString::fromUtf8(arr));
}
Beispiel #30
0
void Server::textRead(){
    QTcpSocket *source = dynamic_cast<QTcpSocket*>(sender());
    QByteArray data = source->readAll();

    QByteArray namePrefix = "/Name::";
    QByteArray challengePrefix = "/Challenge::";
    QByteArray challengeAcceptedPrefix = "/ChallengeAccepted::";
    QByteArray settingsPrefix = "/Settings::";
    QByteArray startPrefix = "/Start::";
    QByteArray turnPrefix = "/Turn::";
    QByteArray locationPrefix = "/Location::";
    QByteArray multiplayerMatchPrefix = "/MultiplayerMatch::";

    if (data.startsWith(namePrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, namePrefix.length(), tempNick.length() - namePrefix.length());
        QString validName = isAvailable(name.toString());
        nickContainer->append(validName);
        if (name != validName){
            source->write("/ValidName::" + validName.toLatin1());
        }
        sendClientList();
    } else if (data.startsWith(challengePrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, challengePrefix.length(), tempNick.length() - challengePrefix.length());
        sendChallenge(source, name);
    } else if (data.startsWith(challengeAcceptedPrefix)){
        QString tempNick(data);
        QStringRef name(&tempNick, challengeAcceptedPrefix.length(), tempNick.length() - challengeAcceptedPrefix.length());
        sendChallengeAccepted(name);
    } else if (data.startsWith(settingsPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, settingsPrefix.length(), tempString.length() - settingsPrefix.length());
        sendSettingsData(values.toString());
    } else if (data.startsWith(startPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, startPrefix.length(), tempString.length() - startPrefix.length());
        sendStartMessage(values);
    } else if (data.startsWith(turnPrefix)){
        QString tempString(data);
        QStringRef name(&tempString, turnPrefix.length(), tempString.length() - turnPrefix.length());
        sendTurnChangeMessage(name);
    } else if (data.startsWith(locationPrefix)){
        QString tempString(data);
        QStringRef values(&tempString, locationPrefix.length(), tempString.length() - locationPrefix.length());
        sendLocationMessage(values);
    } else if (data.startsWith(multiplayerMatchPrefix)){
        QString tempString(data);
        sendPrivateMessage(tempString, multiplayerMatchPrefix);
    } else {
        QTime time = QTime::currentTime();
        QString timeString = time.toString() + " ";
        for (int i = 0; i < clientContainer->size(); ++i){
            clientContainer->at(i)->write(timeString.toLatin1() + data);
        }
    }
}