f



error reading from socket

I am trying to send an integer from Java Client to C++ server. I
figured out how to do the conversion. However, I have a problem reading
from the socket.
This is my code:

int DataInputStream::readInt()//reads one integer from the client
{
   int32_t var1;
   soc->recv((void*)&var1, 4);
   var1 = ntohl(var1);
   return var1;
}

I am assuming that I need a loop, but I cannot figure out which one. I
tried all cases that I could imagine, but none of them worked.
I MUST use recv function. Here is how it is defined:

int recv(void *buffer, int bufferLen)
    throw(SocketException) {
  int rtn;
  if ((rtn = ::recv(sockDesc, (raw_type *) buffer, bufferLen, 0)) < 0)
{
    throw SocketException("Received failed (recv())", true);
  }

  return rtn;
}

Any help is appreciated.

0
msosno01 (13)
7/22/2006 12:19:36 AM
comp.unix.solaris 26025 articles. 2 followers. Post Follow

1 Replies
896 Views

Similar Articles

[PageSpeed] 31

On 2006-07-22, msosno01@gmail.com <msosno01@gmail.com> wrote:
> I am trying to send an integer from Java Client to C++ server. I
> figured out how to do the conversion. However, I have a problem reading
> from the socket.
> This is my code:
>
> int DataInputStream::readInt()//reads one integer from the client
> {
>    int32_t var1;
>    soc->recv((void*)&var1, 4);

You are ignoring the return value of soc->recv, i.e. your function
will happily return some bogus integer value even if less than 4
bytes were read.

>    var1 = ntohl(var1);
>    return var1;
> }
>
> I am assuming that I need a loop, but I cannot figure out which one.

Indeed, a loop is required:

   int bytes_read = 0;
   while (bytes_read < 4) {
      bytes_read += soc->recv((void*)((char*)&var1 + bytes_read),
	 4 - bytes_read);
   }

Andreas.
0
comp
7/23/2006 7:20:12 AM
Reply: