What is the best way to read my socket?

It just gets stuck every time I loop it. He is sitting, waiting to read, but did not read, because ... well, there is nothing 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 is what is called:

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

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

    writeSocket(sockfd, mybuffer);
}

Any suggestions?

+3
source share
1 answer

A TCP socket is a bidirectional stream. He does not know about your message boundaries. To define individual messages, you need your own protocol over TCP. Two Three common approaches:

  • fixed-length messages
  • the length of the message embedded in the message header of a fixed length,
  • explicit message separator, say, newline or \0x1etc. (thanks, @caf).

Change 0:

Some notes about your code:

  • , read(2). -, -1, .. , errno(3); -, 4 , .
  • nBytes == 0 - EOF, .
  • memset().
+8

Source: https://habr.com/ru/post/1790342/


All Articles