【问题标题】:Why I can't read from and write to socket with printf and scanf?为什么我不能用 printf 和 scanf 读写套接字?
【发布时间】:2021-05-09 23:08:06
【问题描述】:

我想知道为什么这段代码不起作用。我的意思是:当服务器和客户端都在运行时,我可以键入并键入没有结果。但是,当我终止客户端时,服务器开始将我之前写入的所有内容输出到客户端应用程序。

完整的 server.c:https://pastebin.com/iXSYLZS3

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define PORT 8080

int main(void)
{
        // some code to initialize connection

        printf("connection accepted!\n");
        fflush(stdout);

        close(0);
        dup(sock);
        while (1) {
                scanf("%s", str);
                printf("%s", str);
                fflush(stdout);
        }

        return(0);
}

完整的client.c:https://pastebin.com/sFmi72ZP

#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
 
#define PORT 8080
 
int main(void)
{
        // some code to initialize connection
 
        printf("connected!\n");
        fflush(stdout);
 
        close(1);
        dup(sock);
        while (1) {
                scanf("%s", str);
                printf("%s", str);
                fflush(stdout);
        }
 
        return(0);
}

【问题讨论】:

    标签: c io sockets


    【解决方案1】:

    它可能看起来“有效”,但这只是偶然。关闭 FILE* 的底层描述符并将其替换为另一个必然会在某些时候混淆 FILE 实现(很可能在那个重要的演示期间)

    安全的方法是使用fdopen从给定的套接字创建一个新的FILE*,然后如果你坚持使用fscanf/fprintf

    fdopen 是 posix 函数,但 dup 也是如此,所以我猜你是在 posix 系统上。

    【讨论】:

      【解决方案2】:

      它有效。我只需要在字符串末尾添加换行符即可冲洗管道。例如。我用过:

      printf("%s\n", str);
      

      代替:

      printf("%s", str);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        • 2012-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-13
        • 1970-01-01
        相关资源
        最近更新 更多