Exemplo n.º 1
0
void ourtrackserv::slotReadClient()
{
  QTcpSocket* clientSocket = (QTcpSocket*)sender();
  int idusersocs = clientSocket->socketDescriptor();

  // Получаем флаг запроса
  char flag;
  if (!clientSocket->getChar(&flag))
  {
    qDebug() << "Error flag read";
    clientSocket->close();
    SClients.remove(idusersocs);
    return;
  }

  switch (flag)
  {
  case FLAG_FIND:
    {
      FindQueryDissect(clientSocket);
      break;
    }
  case FLAG_ADD:
    {
      AddQueryDissect(clientSocket);
      break;
    }
  case FLAG_LIKED:
    {
      LikeQueryDissect(clientSocket);
      break;
    }
  case FLAG_LAST:
    {
      GetLastQueryDissect(clientSocket);
      break;
    }
  case FLAG_PLDOWN:
    {
      PlusDownloadQueryDissect(clientSocket);
      break;
    }
  default:
    {
      break;
    }
  }

  clientSocket->close();
  SClients.remove(idusersocs);
}
Exemplo n.º 2
0
void HttpDaemon::readClient()
{
    if (disabled)
        return;

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

            qDebug() << "Wrote to client";

            if (socket->state() == QTcpSocket::UnconnectedState) {
                delete socket;
                qDebug() << "Connection closed";
            }
        }
    }
}
Exemplo n.º 3
0
void HttpSocket::handleNewConnection()
{
    DBUG;
    while (hasPendingConnections()) {
        QTcpSocket *socket = nextPendingConnection();

        // prevent clients from sending too much data
        socket->setReadBufferSize(constMaxBuffer);

        static const QLatin1String constIpV6Prefix("::ffff:");

        QString peer=socket->peerAddress().toString();
        QString ifaceAddress=serverAddress().toString();
        const bool hostOk=peer==ifaceAddress || peer==mpdAddr || peer==(constIpV6Prefix+mpdAddr) ||
                          peer==QLatin1String("127.0.0.1") || peer==(constIpV6Prefix+QLatin1String("127.0.0.1"));

        DBUG << "peer:" << peer << "mpd:" << mpdAddr << "iface:" << ifaceAddress << "ok:" << hostOk;
        if (!hostOk) {
            sendErrorResponse(socket, 400);
            socket->close();
            DBUG << "Not from valid host";
            return;
        }

        connect(socket, SIGNAL(readyRead()), this, SLOT(readClient()));
        connect(socket, SIGNAL(disconnected()), this, SLOT(discardClient()));
    }
}
Exemplo n.º 4
0
void HttpServer :: readClient()
{
  if (disabled) return;
  QTcpSocket *socket = (QTcpSocket*)sender();
  if( socket->canReadLine()) {

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

    if( tokens[0] == "GET") {
      d->engine.globalObject().setProperty("token", tokens[1]);      
      QScriptValue reply = d->engine.evaluate("reply(token)");
      
      QTextStream os(socket);
      os.setAutoDetectUnicode(true);
      os << reply.toString().toUtf8();
      
      socket->close();
      
      QtServiceBase::instance()->logMessage("Wrote index.html");
      
      if(socket->state() == QTcpSocket::UnconnectedState) {
        delete socket;
        QtServiceBase::instance()->logMessage("Conncetion closed");
        
      }
    }
  }
}
Exemplo n.º 5
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);
    }
}
Exemplo n.º 6
0
void aplist::get_ap_list()
{
    QDataStream in(&tcpSocket);
    quint8 type;
    quint8 request_type;
    char ssid_buf[512] = {0};
    in.setByteOrder(QDataStream::LittleEndian);
    in>>type>>request_type>>n_ap;
    if(type!=0x02)
    {
        tcpSocket.close();
        //error();
    }
    else if(type==0x02)
    {
        in.setByteOrder(QDataStream::LittleEndian);
        if(request_type==0x01)
        {
            for(int i=0;i<n_ap;i++)
            {
                in>>ap_li[i].ssid_len;
                in.readRawData(ssid_buf, ap_li[i].ssid_len);
                ssid_buf[ap_li[i].ssid_len] = '\0';
                ap_li[i].ssid = QString(ssid_buf);
                in>>ap_li[i].encrypt_type;
                in.readRawData((char *)ap_li[i].bssid, sizeof(ap_li[i].bssid));
            }
            show_data();
        }
    }
Exemplo n.º 7
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();

}
Exemplo n.º 8
0
void DataBus::Server::newClientConnected()
{
    while (m_tcpServer.hasPendingConnections())
    {
        // Initialize new DataBus Client
        QTcpSocket *socket = m_tcpServer.nextPendingConnection();
        Client *client = new Client(this);

        if (client->initialize(socket) == false)
        {
            // Error, failed to initialize socsocketket
            if (socket != 0)
            {
                socket->close();
                socket->deleteLater();
                socket = 0;
            }

            continue;
        }

        connect(client, SIGNAL(clientDisconnected(Client*)), this, SLOT(clientDisconnected(Client*)));
        connect(client, SIGNAL(newPacketReceived(Client*)), this, SLOT(processReceivedPacket(Client*)));

        // Add client to list
        addClient(client);
    }
}
Exemplo n.º 9
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;
}
Exemplo n.º 10
0
void mjpegThread::run()
{
    QTcpSocket *socket = new QTcpSocket(this);

    connect(socket, SIGNAL(connected()),this, SLOT(connected()));
    connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected()));
    connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead()));
    
    QUrl url(cfg->get("src1/url"), QUrl::TolerantMode);

    socket->connectToHost(url.host(), 80);

    if(!socket->waitForConnected(5000))
    {
      qDebug() << "Error: " << socket->errorString();
    }


    while (fRun)
    {
        sleep(1);
    }

    socket->close();
}
Exemplo n.º 11
0
void fakeap::get_fake_list()
{
    QDataStream in(&tcpSocket);
    quint8 type;
    quint8 request_type;
    char ssid_buf[512] = {0};
    in.setByteOrder(QDataStream::LittleEndian);
    in>>type>>request_type>>n_fake;
    n_fake = 1;
    ui->fake_num->display(n_fake);
    if(type!=0x02)
    {
        tcpSocket.close();
        //error();
    }
    else if(type==0x02)
    {
        in.setByteOrder(QDataStream::LittleEndian);
        if(request_type==0x02)
        {
            for(int i=0;i<n_fake;i++)
            {
                in>>fake_li[i].ssid_len;
                in.readRawData(ssid_buf, fake_li[i].ssid_len);
                ssid_buf[fake_li[i].ssid_len] = '\0';
                fake_li[i].ssid = QString(ssid_buf);
                in>>fake_li[i].encrypt_type;
                in.readRawData((char *)fake_li[i].bssid, sizeof(fake_li[i].bssid));
            }
            show_data();
        }
    }
Exemplo n.º 12
0
void brain_stroke_server::deal_next_request(){
    puts("deal next");
    //get next request
    deque_mutex.lock();
    if(request_list.size() != 0){
        puts("has next");
        QTcpSocket * client = request_list.front();
        request_list.pop_front();
        deque_mutex.unlock();
        //ignore closing socket
        if(client->state() == QTcpSocket::UnconnectedState || client->state() == QTcpSocket::ClosingState){
            client->close();
            QLOG_DEBUG() << "close client" << client;
            std::cout << "close client:" << client->peerAddress().toString().toStdString() << std::endl;
            //search next from request_list
            deal_next_request();
            return;
        }
        tcp_deal * tcp_deal_thread = new tcp_deal();
        tcp_deal_thread -> set_socket(client);
        connect(tcp_deal_thread, SIGNAL(finished()), this, SLOT(deal_next_request()));
        connect(tcp_deal_thread, SIGNAL(finished()), tcp_deal_thread, SLOT(deleteLater()));
        tcp_deal_thread -> start();
        return;
    }
    deque_mutex.unlock();
    QMutexLocker calculate_flag_mutex_locker(&calculate_flag_mutex);
    //no calculating now
    calculate_flag = false;
    return;
}
Exemplo n.º 13
0
void XSocket::OnClientDisconnection()
{
	qDebug() << "[XSocket::OnClientDisconnection] Disconnected.";
	QTcpSocket* connection = qobject_cast<QTcpSocket*>(sender());
	connection->close();
	connection->deleteLater();
}
Exemplo n.º 14
0
void XSocket::OnClientError(QAbstractSocket::SocketError)
{
	QTcpSocket* connection = qobject_cast<QTcpSocket*>(sender());
	qDebug() << "[XSocket::OnClientError] Client error: " << connection->errorString();
	connection->close();
	connection->deleteLater();
}
Exemplo n.º 15
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();
    //    }
}
Exemplo n.º 16
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 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...";
    }
}
Exemplo n.º 18
0
void HttpDaemon::readClient()
{
    QTcpSocket* socket = (QTcpSocket*)sender();
    if (socket->canReadLine())
    {
        QTextStream os(socket);
        os.setAutoDetectUnicode(true);
        os << "HTTP/1.0 200 Ok\r\n"
            "Content-Type: text/html; charset=\"utf-8\"\r\n"
            "\r\n";

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

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

        socket->close();

        if (socket->state() == QTcpSocket::UnconnectedState)
            delete socket;
    }
}
Exemplo n.º 19
0
void sendRequest(su_Stream& funcObj,void* paraObj,QTcpSocket& tcpSocket){
    (void)paraObj;
    BasicBlock sb;
    QString headFig="<effrequest>";
    QString endFig="</effrequest>";
    serialize(&sb,&headFig);
    sendBasicBlock(&tcpSocket,sb);
    QFile file(funcObj.streamSource);
    if(!file.open(QIODevice::ReadOnly)){
        tcpSocket.close();
        return;
    }
    if(funcObj.knownSize)
        funcObj.streamLength=file.size();
    else
        funcObj.streamLength=0;
    serialize(&sb,&funcObj);
    sendBasicBlock(&tcpSocket,sb);
    QDataStream in(&file);
    sendStreamData(&tcpSocket,in,funcObj.streamLength);
    file.close();
    in.unsetDevice();
    serialize(&sb,&endFig);
    sendBasicBlock(&tcpSocket,sb);
}
Exemplo n.º 20
0
void MainWindow::recvMsg()
{   
    QTcpSocket * tcpSocket = (QTcpSocket*)sender();
    QDataStream dataStream(tcpSocket);

    QString str;
    foreach(stUserInfo user,list)
    {
       if(user.pTcpSocket == tcpSocket)
       {
            // without connect message
           str = processRecvMsg(tcpSocket);
           ui->textEdit->append(str);

           if(str.compare("Exit")==0||str.right(7).compare("SIGN_UP")==0 )
           {
               tcpSocket->close();
           }
           break;
       }
    }

    /*
    QByteArray arrIDChk(tcpSocket->readAll());
    QString strIDChk(arrIDChk.data());
    if(strIDChk.compare("김봉상") == 0)
    {

    }

    */
}
Exemplo n.º 21
0
QString Protocol::MsgSender::getGroupSig(QString gid, QString to_id)
{
    if ( group_sigs_.contains(gid+to_id) )
        return group_sigs_.value(gid+to_id);

    QString msg_sig_url = "/channel/get_c2cmsg_sig2?id="+ gid +"&to_uin=" + to_id +
        "&service_type=0&clientid=5412354841&psessionid=" + CaptchaInfo::instance()->psessionid() +"&t=" + QString::number(QDateTime::currentMSecsSinceEpoch());

    QHttpRequestHeader header;
    QString host = "d.web2.qq.com";
    header.setRequest("GET", msg_sig_url);
    header.addValue("Host", host);
    header.addValue("Content-Type", "utf-8");
    header.addValue("Referer", "http://d.web2.qq.com/proxy.html?v=20110331002");
    header.addValue("Cookie", CaptchaInfo::instance()->cookie());

    QTcpSocket fd;
    fd.connectToHost(host, 80);
    fd.write(header.toString().toAscii());

    QByteArray result;
    socketReceive(&fd, result);
    fd.close();

    int sig_s_idx = result.indexOf("value")+8;
    int sig_e_idx = result.indexOf('"', sig_s_idx);
    QString sig = result.mid(sig_s_idx, sig_e_idx - sig_s_idx);

    group_sigs_.insert(gid+to_id, sig);

    return sig;
}
Exemplo n.º 22
0
void NewGame::refreshGames()
{
    this->ui->listRefresh->setEnabled(false);
    this->ui->listGame->clear();
    unsigned int ip;
    unsigned int netmask = 0xffffff00;
    foreach (QNetworkInterface it, QNetworkInterface::allInterfaces())
        foreach (QHostAddress addr, it.allAddresses())
            if (addr.toIPv4Address() && 0xff000000 != 0x7f000000)
                ip = addr.toIPv4Address();
    unsigned int networkaddr = ip & netmask;
    for (unsigned int i = 1; i < 256; i++)
    {
        unsigned int currentIp = networkaddr + i;
        QTcpSocket* s = new QTcpSocket();
        s->connectToHost(QHostAddress(currentIp), 1338);
        static_cast<MainWindow*>(this->parent())->print_status("Scanning ...\tCurrent : " + QHostAddress(currentIp).toString());
        if (s->waitForConnected(5))
        {
            this->ui->listGame->addItem(new QListWidgetItem(QHostAddress(currentIp).toString()));
            QCoreApplication::processEvents();
            // tell the slave this is just a search request
            s->write("s", 1);
            s->close();
        }
    }
    static_cast<MainWindow*>(this->parent())->print_status("End of scan");
    this->ui->listRefresh->setEnabled(true);
}
Exemplo n.º 23
0
void ClientServer::incomingConnection(qintptr handle)
{


#ifdef DEBUG
    static long long counter = 0;
    qDebug() << "incoming client connection on port : " << this->port << " #" << counter;
    ++counter;
#endif
    if (this->relayerServer)
    {
        if (this->relayerServer->handerClient(handle))
        {
#ifdef DEBUG
    qDebug() << "incoming client connection handled";
#endif
        }
        else
        {
#ifdef DEBUG
    qDebug() << "incoming client connection handled failed";
#endif

        // create the socket and close the connection
            QTcpSocket *socket = new QTcpSocket(this);
            socket->setSocketDescriptor(handle);
            socket->close();
            socket->deleteLater();
        }
    }
}
Exemplo n.º 24
0
void            HostedCall::receiveNewTcpConnection()
{
    int             id;
    bool            ok = false;
    QTcpSocket      *sock = this->_tcpServer.nextPendingConnection();
    if (sock != 0)
    {
        std::cout << "Receive new tcp connection" << std::endl;
        QString ip = sock->peerAddress().toString();
        QList<Callee>::iterator it = this->_allowedUser.begin();
        for (; it != this->_allowedUser.end(); ++it)
        {
            if (it->getIp() == ip)
            {
                ok = true;
                it->setSock(sock);
                connect(sock, SIGNAL(readyRead()), &this->_worker, SLOT(onReadSomething()));
                connect(sock, SIGNAL(disconnected()), &this->_worker, SLOT(onClientDisconnectedFromCall()));
                connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onSocketError(QAbstractSocket::SocketError)));
                id = this->_connectedUsers.count() + 1;
                this->_container.addProducer(id);
                this->sendWelcome(id, sock);
                this->sendParticipantStatusUpdate(true, id, it->getUsername());
                this->sendUdpReady(sock);
                this->_connectedUsers[id] = Callee(it->getIp(), it->getUsername());
                this->_connectedUsers[id].setSock(sock);
                this->_allowedUser.erase(it);
                break;
            }
        }
        if (!ok)
            sock->close();
    }
}
//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;
}
Exemplo n.º 26
0
/*!
    \internal
 */
void QWebSocketServerPrivate::onCloseConnection()
{
    if (Q_LIKELY(currentSender)) {
        QTcpSocket *pTcpSocket = qobject_cast<QTcpSocket*>(currentSender->sender);
        if (Q_LIKELY(pTcpSocket))
            pTcpSocket->close();
    }
}
Exemplo n.º 27
0
void TSock::declineConnection() {
    QTcpSocket *s = server.nextPendingConnection();
    if (s == NULL)
        return;

    s->close();
    delete s;
}
Exemplo n.º 28
0
void ServerLight::readyRead() {
    BL_FUNC_DEBUG
    static QByteArray array = "";
    QByteArray lectura = "";
    QTcpSocket *socket = (QTcpSocket *) sender();
    lectura = socket->readAll();
    g_buffers[socket]  += lectura;
    array += lectura;
    QString mensaje = _("Mensaje desde: ")+ socket->peerAddress().toString() + "\n";
    
    QString texto(g_buffers[socket]);

    fprintf(stderr, "\nPaquete recibido:\n");
    fprintf(stderr, array);
    fprintf(stderr, "\nPaquete finalizado :\n");
    fprintf(stderr, QString::number(array.size()).toAscii());
    fprintf(stderr, "\nFin Paquete recibido :\n");
    
    /// Si se detecta el final de la transmision se procesa la informacion.
    if (texto.contains("</DOCUMENT>", Qt::CaseInsensitive)) {
    
	if (texto.contains("<GETCOMMAND>categoria_articulo</GETCOMMAND>", Qt::CaseInsensitive)) {
	    fprintf(stderr, categoryArticleXML().toAscii() );
	    socket->write(categoryArticleXML().toAscii());
	    /// Hay que cerrar el socket despues del envio.
	    g_buffers[socket] = "";
	    g_buffers.remove(socket);
	    socket->close();
	
        } else if (texto.contains("<PUTCOMMAND>ticket_data</PUTCOMMAND>", Qt::CaseInsensitive)) {
	    /// Nos han mandado la informacion de un ticket.
	    processTicketDataXML(texto);
	    g_buffers[socket] = "";
	    g_buffers.remove(socket);
	    socket->close();
        } else {
	    //fprintf(stderr, "--NO ENTIENDO--");
	} // end if

	/// Como se ha completado la recepcion de datos y se han procesado, se resetea el buffer de entrada.
	array = "";

    } // end if

    
}
Exemplo n.º 29
0
void Client::discardClient() {
    qDebug()<<"Client::discardClient";
    QTcpSocket* socket = (QTcpSocket*)sender();
    socket->close();

    // need to discard the receiver

}
Exemplo n.º 30
0
void NewOutputHandler::newSunspotOutput(int dataType)
{
    QTcpSocket *socketConnection = new QTcpSocket();
    QByteArray data = generateXmlData(dataType);
    socketConnection->connectToHost(QHostAddress::LocalHost, 6998);
    socketConnection->write(data);
    socketConnection->close();
}