Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Sending a File with its name with QTcpSocket



  • Hello Everyone,

    this may seem easy but i'm having a hard time sending a File with its name to another Device using QTcpSocket and QTcpServer.

    Here's the Code of the Sender

    if (!TCFile.open(QIODevice::ReadOnly))
    {
    printf("could not open File");
    }
    else
    {
    printf("File opened!");
    qint64 Size = TCFile.size();
    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly); 
    out.setVersion(QDataStream::Qt_5_4);		  
    QString FileName = TCFile.fileName();		   
    out << quint32(0) << FileName;				   
    QByteArray	q = TCFile.readAll();			  
    block.append(q);				              
    TCFile.close();
    out.device()->seek(0);
    out << (quint32)(block.size()) - sizeof(quint32);
    socket->write(q);
    qint64 x = 0;
    while (x < Size)
    {
    qint64 y = socket->write(q);
    x += y;
    }
    

    The Server Side:

    QDataStream in (m_socket);
    	in.setVersion(QDataStream::Qt_5_4);
    
    if (m_Blocksize = 0) {
    	if (m_socket->bytesAvailable() < sizeof(quint32))
    		return;
    	in >> m_Blocksize;
    }
    
    if (m_socket->bytesAvailable() < m_Blocksize)
    	return; 
    
    QString FileName; 
    in >> FileName;
    
    
    QByteArray line = m_socket->readAll(); 
    QString FilePath = "C:\\test"; 
    
    QFile target(FilePath + "/" + FileName);
    
    
    if (!target.open(QIODevice::WriteOnly)) { //opening the File to write the incoming Data to it 
    
    	printf("can't open File for writing");
    }
    else
    {
    	target.write(line); //Writing the byte Array line to the target file 
    	printf("File received \n");
    	target.close();
    }
    

    This doesn't work as i get the Error can't open File for writing. When I manually type the name of the file on the Server side it does work. But as I'm trying to send multiple files i want this to be done autmatically. How can i make the Code above work??

    Thanks !!



  • Hi,
    please correct the path to follow Qt platform independent convention. Like it's described in many places throughout the documentation, i.e. here: https://doc.qt.io/qt-5/qdir.html



  • @JohnSRV
    It may or may not be related to your error. But regardless you cannot write server/receiver code which relies on m_socket->bytesAvailable() and m_socket->readAll() cooperating to read everything the client has sent in one go. You need to understand that readAll() only reads whatever is presently available, and that may not be the complete data sent by the client.

    • Only repeated reading can achieve that. Rewrite your code receiver-side to use slots.
    • Or use QDataStream::startTransaction() etc. to hide this from your code level, but it still works that way internally.

    Look at the various Qt Fortune Client/Server examples.


Log in to reply