Sending files via QTcpSocket



  • Hello. Sorry for my English (i'm from Russia), i hope, you will understand my problem.
    I'm trying to send files via QTcpSocket. For sending files i create new QThread.
    @void MainWindow::slot_send_file_menu_handler()
    {
    QTcpServer* server_to_send = new QTcpServer(this);
    if(!server_to_send->listen(QHostAddress::Any, 1234))
    return;
    QObject::connect(server_to_send, SIGNAL(newConnection()), this, SLOT(slot_new_connection()));
    }@
    When client connects to server, server starts to send file in new thread
    @void MainWindow::slot_new_connection()
    {
    QTcpSocket* socket_to_send = ((QTcpServer*)(sender()))->nextPendingConnection();
    SendFileThread* thread = new SendFileThread();
    thread->set_params(socket_to_send, QString("d:\work\mini.exe"));
    }@
    SendFileThread.cpp
    @void SendFileThread::set_params(QTcpSocket *socket, QString path)
    {
    _socket = socket;
    _path = path;
    start();
    }

    void SendFileThread::run()
    {
    QFile file_to_send(_path);
    QDataStream read(&file_to_send);
    read.setVersion(QDataStream::Qt_4_5);
    file_to_send.open(QFile::ReadOnly);

    QByteArray bArray;
    QDataStream dStream(&bArray, QIODevice::WriteOnly);
    dStream.setVersion(QDataStream::Qt_4_5);
    
    dStream << quint64(file_to_send.size());
    dStream << _path;
    
    _socket->write(bArray);
    _socket->waitForBytesWritten();
    
    long lBytes = 0;
    long bytesSend = 0;
    char *ch = new char[1024];
    ch[1023] = '\0';
    
    while(!read.atEnd())
    {
        int l = read.readRawData(ch, sizeof(char)*1023);
        QByteArray ba(ch, sizeof(char)*l);
        lBytes = _socket->write(ba, sizeof(char)*l);
        bytesSend += lBytes;
        _socket->waitForBytesWritten();
    
        if (-1 == lBytes){
            qWarning() << "Error";
            _socket->close();
            return;
        }
    }
    

    }@

    But i'v got a problem, while receiving (or sending) file. When last block is sending, program crashed. When i have trying to send small files, program crashes immediately.
    Please, help me to solve this problem or, may be, show example how to send large files via QTcpSocket in different threads.
    I hope, it's all clear in my problem. Sorry for my English.
    Thanks for help.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.