QFile file(fileName); if(!file.open(QIODevice::ReadOnly)) { // err str return false; } if(!socket->isValid()) { return false; } socket->waitForConnected(); QDataStream read(&file); QByteArray arr; QDataStream out(&arr, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_7); char data[PACKET_SIZE]; int readed; out << quint16(0) << QString("file") << QFileInfo(file.fileName()).fileName() << file.size(); out.device()->seek(0); out << quint16(arr.size() - sizeof(quint16)); socket->write(arr); socket->flush(); while(!read.atEnd()) { readed = read.readRawData(*(&data), PACKET_SIZE); QByteArray array(*(&data), PACKET_SIZE); socket->write(array); }
QTcpSocket *clientSocket = (QTcpSocket *)sender(); QDataStream in(clientSocket); in.setVersion(QDataStream::Qt_4_7); qDebug() << "read" << clientSocket->bytesAvailable(); for(;;) { if(!nextBlockSize) { if(clientSocket->bytesAvailable() < sizeof(quint16)) break; in >> nextBlockSize; } if(clientSocket->bytesAvailable() < nextBlockSize) break; QString type; in >> type; if(type == "file") { // принимаем файл QString fileName; quint64 size; in >> fileName; in >> size; QFile file(fileName); if(!file.open(QIODevice::WriteOnly)) { qDebug() << "can't open file to write"; return; } qDebug() << "----------" << fileName << size; QDataStream fileOut(&file); int readed; quint64 done = 0; while(done < size) { /*readed = 0; while(readed == 0) readed = clientSocket->waitForReadyRead(-1); if(readed == -1) { qDebug() << "socket err"; return; }*/ QByteArray tmp; tmp = clientSocket->readAll(); fileOut.writeRawData(tmp.data(), tmp.size()); done += tmp.size(); qDebug() << "writed" << tmp.size(); break; } qDebug() << "done"; file.close(); return; } else if (type == "text") { } nextBlockSize = 0; }
out << quint16(0) << QString("file") << QFileInfo(file.fileName()).fileName() << file.size() << "сам файл"; out.device()->seek(0); out << quint16(arr.size() - sizeof(quint16));