简体   繁体   中英

Send integer from TCP socket in C to Qt TCP socket

I'm currently trying to implement basic client-server file transfer program using TCP sockets. Client is being written in C++/Qt and the server in C. I encountered great difficulty when trying to send the file size from server to client (integer value). Below are the code samples.

C server:

if(fileExists == '1')
{
   fp = fopen(filename, "r");
   fseek(fp, 0L, SEEK_END);
   fileSize = ftell(fp);
   printf("%d\n", fileSize);
   send(client_socket, &fileSize, sizeof(fileSize), 0);
}

Qt Client:

void Client::receiveFile(QString filename)
{
    qint32 fileSize;
    clientSocket->waitForReadyRead(1000);
    clientSocket->read(fileSize);
    qDebug() << fileSize;
}

The problem is that C calculates the file size properly as 40435408 and sends it over to the client which says the size is 32767. It's obvious that the problem lies on the client side. I tried to figure out the problem for almost whole day and failed. I realize that this is some simple and stupid mistake I made and I apologize for asking such dumb question. I'm a complete begginner. Can anyone help?

When you call clientSocket->read(fileSize); , you are in fact calling QByteArray QIODevice::read(qint64 maxSize) . Which means you are reading up to an undefined (as fileSize is not initialized) amount of bytes from the TCP socket and discard it immediatly, as you don't use the return value.

I think you are trying to use qint64 QIODevice::read(char *data, qint64 maxSize) , so your code should look like this:

qint32 fileSize = 0;
clientSocket->waitForReadyRead(1000);
if (clientSocket->bytesAvailable() >= sizeof(fileSize)) {
    clientSocket->read(&fileSize, sizeof(fileSize));
} else {
    qWarning() < "Only received" << clientSocket->bytesAvailable() << "bytes: " << clientSocket->readAll().toHex(' ');
}
qDebug() << fileSize;

Note that I would not use this code in any software that is more than a proof of concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM