How to disable recv () function in C ++?

I have a program running on a server that interacts with another program running on the client. They both send data and files back and forth.

I notice that whenever there is a socHandler.read () function for reading data entering a socket), it gets stuck waiting for data to be received.

This is what the function looks like.

int CSocHandler::read(char * inBuffer, INT64 iBytesToRead){ bool blReadMore=false; int retVal = 0; int iOutputPointer = 0; do{ blReadMore = false; if (iStartOfBuffer == iEndOfBuffer) { //Buffer empty if (blClosed ) { return -1; } iStartOfBuffer = 0; iEndOfBuffer = 0; size_t bufferRemaining = BUFFER_SIZE-iEndOfBuffer; int bytesRecvd = recv( sock, &buffer[iEndOfBuffer], (int)iBytesToRead<bufferRemaining?iBytesToRead:bufferRemaining), 0 ); if ( bytesRecvd <= 0) { close(); Yield(); return retVal; } } } while(blReadMore); return retVal; } 

The sock variable is a SOCKET type and is a global variable defined elsewhere. How to set parameters or make this recv () call non-blocking only for this function call and not affect any other function?

I believe this is where he gets stuck waiting for data, and I want to make it a timeout after X seconds.

+4
source share
2 answers

Call select() to ask if the socket has any pending data, and then calls recv() to read it.

+3
source

Use select(2) on the socket before recv .

Using Perl syntax, it will look like

 sub read_with_timeout { my ($sock, $bytes_to_read, $timeout) = @_; my $sel = IO::Select->new($sock); my $end_time = Time::HiRes::time() + $timeout; my $buf = ''; while ($bytes_to_read) { $timeout >= 0 && () = $sel->can_read($timeout); or die("Timeout"); my $rv = sysread($sock, $buf, $bytes_to_read, length($buf)); die "read: $!" if !defined($rv); die "Premature eof" if !$rv; $bytes_to_read -= $rv; $timeout = $end_time - Time::HiRes::time(); } return $buf; } 

can_read - call select(2) .

+3
source

All Articles