简体   繁体   中英

How can I better read my socket?

This just gets stuck every time I loop it. It sits waiting to read but never reads anything, because, well.. there's nothing left to read.

Here's the read function:

int  readSocket(int sockfd, char* buffer) {

    FILE* file;
    file = fopen("logfile.txt","a+");

    char code[5];

    while(1) {

        int nBytes = read(sockfd, buffer, MY_BUFFER_SIZE);
        fprintf(file,"S->C: %s",buffer);

        strncpy(code, buffer,4); 
        code[4]='\0';



            if (nBytes == 0) break;

        memset(buffer, 0, MY_BUFFER_SIZE);

    }
    fclose(file);
    return codeParser(atoi(code));
}

Here's what's calling it:

while (1) {
    serverCode = readSocket(sockfd, mybuffer);
    if (serverCode == 221) break;

    fflush (stdout);
    buffer = fgets (mybuffer, 1024, stdin); 

    writeSocket(sockfd, mybuffer);
}

Any suggestions?

TCP socket is a bi-directional stream. It does not know about your message boundaries. You need your own protocol on top of TCP to figure out separate messages. Two Three common approaches are:

  • fixed-length messages,
  • length of the message embedded into fixed-length message header,
  • explicit message delimiter, say a new-line, or \\0x1 , etc. (thanks, @caf).

Edit 0:

Some notes about your code:

  1. Always check return values of system calls like read(2) . First, it might be -1 , ie an error, so you have to examine errno(3) ; second, you might read less then 4 bytes you are expecting.
  2. nBytes == 0 is the EOF case, meaning other side closed the connection.
  3. You don't need the memset() there.

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