Mike G
Mike G

Reputation: 4959

Two consecutive socket reads, second read not working

Below I have a code segment from my server code and client code. My client sends an integer to the server which is received successfully, then I send a string of length str_len to the server. The second read in the server is not working, it is blocking and not reading anything. When I exit the client the server prints that it hasnt read anything. What is wrong?

            //Server code

            bzero(buffer,256);
            n = read(newsockfd,buffer,255);
            if (n < 0) error("ERROR reading from socket");
            unsigned int *length = new unsigned int;
            memcpy(length, buffer, sizeof(int));
            cout << "Length : " << *length << endl;
            int len = *length + 1;
            char buffIn[len+1];
            bzero(buffIn,len);
            //ok msg?
            n = read(newsockfd,buffIn,len);
            if (n < 0) error("ERROR reading from socket");
            cout << "value of n" << n << endl;
            printf("Received : %s\n", buffIn);


            //client method

            void send(string req)
            {
                //Send string len
                unsigned int str_len = req.length();
                //str_len = 3000;
                write(socketFd, &str_len, sizeof(str_len));
                //Send string
                const char *str_req = req.c_str();
                printf("%s\n",str_req);
                cout << "Str len is : " << strlen(str_req) << endl;
                write(socketFd, str_req, strlen(str_req) + 1);
                cout << "write done " << endl;
            }

Upvotes: 0

Views: 1533

Answers (2)

Dampsquid
Dampsquid

Reputation: 2474

You read the str length in with a read of 255 bytes from the socket, thus pulling in the first 251 ( assuming 32bit integers) of your data. So when u ask for the rest of the string your asking for an additional 251 Bytes which arn't sent and thus the read call blocks.

read the length into an integer

unsigned int length;
n=read(newsockfd,&length, sizeof(length));

in your current code snippets your not deleteing the length

unsigned int *length = new unsigned int;

which will cause a small memory leak.

As Rob states in his answers you should check the return number of bytes read, not just check for a returned error

Upvotes: 0

Robᵩ
Robᵩ

Reputation: 168616

Consider this line:

n = read(newsockfd,buffer,255);

You never subsequently check the precise value of n. You check to see if the function failed, but you do not check to see how many bytes were read. Hint: in your case, it is more than sizeof (int).

Try this instead:

n = read(newsockfd, buffer, sizeof(int));

N.b.: Under other circumstances, it could also be less than sizeof(int). You must handle that condition, also.

Upvotes: 6

Related Questions