Qt-interest Archive, September 2002
A problem about network programming with QT and standard C
Message 1 in thread
Recently I use QT and standard C to program a network C/S.
I use standard C to program a server, and use qt to program a client.
When I transfer the file from server to client, it's good.
in server the code is:
if( ( fp = fopen( "./test.tar.gz", "r" ) ) == NULL )
{
exit(0);
}
else
{
while( !feof( fp ) )
{
len = fread( str, sizeof(char), MAXLINE, fp );
if( send( new_fd, str, len, 0 ) == -1 )
{
close( new_fd );
exit(0);
}
}
}
in client the code is:
char str[MAXLINE];
QString sTemp;
int len;
bool sign = TRUE;
sTemp = "test.tar.gz";
QFile file( sTemp );
if ( file.open( IO_Raw | IO_WriteOnly ) == false )
{
return;
}
QDataStream ds( &file );
while ( sign )
{
len = m_pSsocket->readBlock( str, MAXLINE );
if ( (len == 0) || (len == -1) )
{
sign = FALSE;
}
else
{
ds.writeRawBytes( str, len );
}
}
ds.unsetDevice();
file.close();
But when I transfer the file from client to server, it has a mistake. The
file which the server received is shorter than the file which the client
sent. The difference less than 4096 bytes. It means:
Length1 ( the length of the file in client ) - Length2 ( the length of the
file in server ) < 4096
in server the code is:
if( ( fp = fopen( "./sth.txt", "w" ) ) ==NULL )
{
exit(0);
}
else
{
sign = 1;
which( sign )
{
if( ( len = recv( new_fd, str, MAXLINE, 0 ) ) == -1 )
{
close( new_fd );
exit(0);
}
if( len == 0 )
{
sign = 0;
}
else
{
fwrite( str, sizeof(char), len, fp );
}
}
}
in client the code is:
QFile file( "sth.txt" );
if ( file.open( IO_Raw | IO_ReadOnly ) == false )
{
return;
}
QDataStream sth( &file );
char str[MAXLINE];
int i, step, len;
step = file.size() / MAXLINE;
for ( i = 0; i < step; ++i )
{
sth.readRawBytes( str, MAXLINE );
m_pSsocket->writeBlock( str, MAXLINE );
}
len = file.size() - MAXLINE * step;
sth.readRawBytes( str, len );
m_pSsocket->writeBlock( str, len );
sth.unsetDevice();
file.close();
Could you help me? Thanks in advance.
Best regards,
Qi Liang