c - TCP client/server send/receive files -
i writing tcp server/client program , want send files server client. here code not work sending file. use recv()
, send()
send files. in advance.
client side:
char *location = "/home/kostas/downloads/download.txt"; file *download = fopen( location, "w+" ); if( download == null ) { printf( "error\n" ); fflush( stdout ); } int transfer = 0; memset( buffer, 0, 1024 ); while( ( transfer = recv( connfd, buffer, 1024 , 0 ) > 0 ) ) { int write = fwrite( buffer, sizeof( char ), transfer, download ); memset( buffer, 0, 1024 ); if( ( transfer == 0 ) || ( transfer != 1024 ) ) { break; } } memset( buffer, 0, 1024 ); if( read( connfd, buffer, sizeof( buffer ) ) < 0 ) { printf( "read error\n" ); fflush( stdout ); }
server side :
//i filename read/write file *file = fopen( filename, "r"); memset( buffer, 0, 1024 ); int = 0; while( ( = fread( buffer, sizeof( char ), 1024, file ) ) < 0 ) { if( send( connfd, buffer, i, 0 ) < 0 ) { printf( "error\n" ); fflush( stdout ); } memset( buffer, 0, 1024 ); }
i not know i'm doing wrong? after intend use posix threads achieve file transfer.
while( ( transfer = recv( connfd, buffer, 1024 , 0 ) > 0 ) ) { int write = fwrite( buffer, sizeof( char ), transfer, download );
you here.
memset( buffer, 0, 1024 );
pointless. remove.
if( ( transfer == 0 ) || ( transfer != 1024 ) ) { break; }
transfer
(a) cannot 0 @ point, , (b) can between 1 , 1024 here. there no reason stop if isn't 1024. remove block.
memset( buffer, 0, 1024 );
pointless. remove.
if( read( connfd, buffer, sizeof( buffer ) ) < 0 ) { printf( "read error\n" ); fflush( stdout ); }
you need store read()
result in variable, and:
- test -1, indicates read error, should print, via
perror()
orstrerror()
- test zero, indicates end of stream
- otherwise use read count in following code, have above.
but don't know why you're reading @ point. input exhausted or read error has occurred. remove it.
memset( buffer, 0, 1024 );
pointless. remove.
int = 0;
the initialization pointless. remove.
while( ( = fread( buffer, sizeof( char ), 1024, file ) ) < 0 ) { if( send( connfd, buffer, i, 0 ) < 0 ) { printf( "error\n" );
at point, again, should print error, mentioned above. printing 'error' useless. when happens, want know was, , have go , modify code find out.
memset( buffer, 0, 1024 );
pointless. remove.
Comments
Post a Comment