簡體   English   中英

為什么我不能用 printf 和 scanf 讀寫套接字?

[英]Why I can't read from and write to socket with printf and scanf?

我想知道為什么這段代碼不起作用。 我的意思是:當服務器和客戶端都在運行時,我可以鍵入並鍵入沒有結果。 但是,當我終止客戶端時,服務器開始將我之前寫入的所有內容輸出到客戶端應用程序。

完整的服務器。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);
}

完整客戶端.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);
}

它可能看起來“有效”,但這只是偶然。 關閉FILE*的底層描述符並將其替換為另一個必然會在某些時候混淆 FILE 實現(很可能在那個重要的演示期間)

安全的方法是使用fdopen從給定的套接字創建一個新的FILE* ,然后如果您堅持使用它,則使用fscanf / fprintf

fdopen是 posix function,但dup也是如此,所以我猜你是在 posix 系統上。

有用。 我只需要在字符串末尾添加換行符即可刷新 pipe。 例如。 我用了:

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

代替:

printf("%s", str);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM