简体   繁体   中英

C: printf non printing \n

In C, I ask the server to print the content of any messages that it receives. All messages follow the format: "Message: /counter/".

while (1){
            length = sizeof(struct sockaddr);
    /*      receive from client */
            lenstr = recv(newfd, buff, 20000, 0);
            if (lenstr == -1){
                perror("recv(): ");
                exit(1);
            }
            buff[lenstr] = '\0';
            printf("Received: %s \n", buff);
    /*        send back to client*/
            if (send(newfd, buff, lenstr, 0) < 0){
                perror("send(): ");
                exit(-1);
            }

When I run the server, messages appear one after the other, without going to the new line. What am I missing here? (connection is TCP here) Thanks.

The data it receives from the socket may contain zeroes or control characters. These should not be printed.

Try using the following function to dump received data into stdout . It replaces all non-printable characters with a dot:

void dump_buf(char const* buf, size_t buf_len) {
    char const* buf_end = buf + buf_len;
    while(buf != buf_end) {
        char c = *buf++;
        putchar(isprint(c) ? c : '.');
    }
    putchar('\n');
}

// ...

lenstr = recv(newfd, buff, 20000, 0);
if (lenstr == -1) {
    perror("recv(): ");
    exit(1);
}
dump_buf(buff, lenstr);

TCP doesn't have "messages", it handles continuous byte streams in both directions. You are just reading whatever is less between the received data up to that instant and your 2000. Perhaps you really want Stream Control Transmission Protocol ? Or mark message ends in some way (perhaps by '\\n'), and read character by character? Or just read the length of a single message (if they are fixed length, that is)?

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