Important: Please read the Qt Code of Conduct -

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))
    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"));
    @void SendFileThread::set_params(QTcpSocket *socket, QString path)
    _socket = socket;
    _path = path;

    void SendFileThread::run()
    QFile file_to_send(_path);
    QDataStream read(&file_to_send);

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


    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