简体   繁体   中英

Read from TCP socket C

I don't understand why function read always return -1. I want to read from socket until '\\n' appear!

    char* msg = (char*)malloc(sizeof(char)*120);
    nleft = sizeof(msg);
    while(nleft>0){
        n = read(fdTcp, msg, nleft);
        if(n == -1){
            printf("error reading UPC\n");
            exit(1); //error
        }   
        else if (n == 0){
            printf("end of reading EOF\n");
            break; //closed by peer
        }   
        nleft-=n;
        msg += n;
    }
    nread = n-nleft;
    msg[nread] = '\0';
    printf("mensagem do CS: %s\n", msg);

Thanks in advance!

char* msg = (char*)malloc(sizeof(char)*120);
nleft = sizeof(msg);

Since msg is a char* , nleft will be the number of bytes in a char* . I don't think that's what you want.

As for answering your real question:

but I don't now how many bytes I will read, I want to ready until I reach '\\n' how can I do it?

You have two choices. The terrible option is to read one byte at a time until you read a newline. The better option is to read as much as you can and check for a newline. If you read past the newline, great, that's just less work you'll have to do on your next pass. In pseudo-code:

  1. If there is not at least one newline in the buffer, skip to step 5.

  2. Extract the bytes up to the first newline from the buffer and process them.

  3. Move any bytes past the newline to the beginning of the buffer and adjust the size of the buffer to include just those bytes.

  4. Go to step 1.

  5. Do a blocking read and append the data to the buffer.

  6. Go to step 1.

I assume your socket successfuly open socket connection. Then file discriptor is 1 that means that ready ro read data. You tried to read socket but you took an error with -1. Generally this error appear when the socket was closed. If you took -1, socket was closed. If took 0 that means timeout for read socket data. On the other hand if you took more than 0 this means, read how much bytes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM