Telnet和C Server:未清除的流

时间:2017-02-09 14:34:21

标签: c server stream telnet

我创建了一个有效的连接,两个有效的文件tx(传输)和rx(接收),并尝试接收telnet发送的日期并将数据发送到telnet。 这是关键代码部分:

for(i = 0; i < 3; i++){
            fprintf(tx, "Send me a message\n");
            while(1){
                c = fgetc(rx);
                fputc(c, stdout);
                if(c == '\n')
                    break;
            }
            fprintf(tx, "Thank you! \n");
}

(完整代码见下文)

现在,我启动此服务器并通过telnet连接到它,发送一些文本。这是结果:

ocean@oogway:~/cTest/Server$ telnet ::1 2017
Trying ::1...
Connected to ::1.
Escape character is '^]'.
hello
how are you
nice to meet you
Send me a message
Thank you! 
Send me a message
Thank you! 
Send me a message
Thank you! 
Connection closed by foreign host.

但是,看看我的代码,我本来希望看到:

Send a message
Hello
Thank you!
Send a message
How are you
Thank you!
...

为什么telnet只在服务器终止时打印出日期?

完整代码:

#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

static const int LISTEN_PORT = 2017;


static void die(const char *msg){
    perror(msg);
    exit(EXIT_FAILURE);
}

int main (void){
    int sockfd, flag;
    flag = 1;
    struct sockaddr_in6 host_addr;

    sockfd = socket(PF_INET6, SOCK_STREAM, 0);
    if(sockfd == -1)
        die("socket");

    host_addr.sin6_family = AF_INET6;
    host_addr.sin6_port = htons(2017);
    host_addr.sin6_addr = in6addr_any;

    if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(int))
    == -1)
        die("setsockopt");

    if(bind(sockfd, (const struct sockaddr *)&host_addr, 
        sizeof(host_addr)) ==  -1)
        die("bind");
    if(listen(sockfd, SOMAXCONN) == -1)
        die("listen");

    while(1){
        int client = accept(sockfd, NULL, NULL);

        if(client == -1)
            die("accept");

        int client2 = dup(client);

        if(client2 == -1)
            die("dup");
        FILE *tx;
        FILE *rx;

        tx = fdopen(client, "w");
        rx = fdopen(client2, "r");

        if(!tx || !rx)
            die("fdopen");
        int c;
        int i;
        for(i = 0; i < 3; i++){
            fprintf(tx, "Send me a message\n");
            while(1){
                c = fgetc(rx);
                fputc(c, stdout);
                if(c == '\n')
                    break;
            }
            fprintf(tx, "Thank you! \n");
        }
        break;
    }
    exit(EXIT_SUCCESS);
}

0 个答案:

没有答案