为什么我不能用 printf 和 scanf 读取和写入套接字?
Why I can't read from and write to socket with printf and scanf?
我想知道为什么这段代码不起作用。我的意思是:当服务器和客户端都是 运行 时,我可以输入和输入没有结果。但是,当我终止客户端时,服务器开始输出我之前写入客户端应用程序的所有内容。
完整 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);
}
有效。我只需要在要冲洗的管道的字符串末尾添加换行符。例如。我用过:
printf("%s\n", str);
而不是:
printf("%s", str);
它可能看起来 'work',但那只是偶然。关闭 FILE*
的底层描述符并将其替换为另一个一定会在某些时候混淆 FILE 实现(最有可能在那个重要的演示期间)
安全的方法是使用 fdopen
从给定的套接字创建一个新的 FILE*
,然后如果您坚持使用 fscanf
/fprintf
。
fdopen
是一个 posix 函数,但 dup
也是,所以我猜你在 posix 系统上。
我想知道为什么这段代码不起作用。我的意思是:当服务器和客户端都是 运行 时,我可以输入和输入没有结果。但是,当我终止客户端时,服务器开始输出我之前写入客户端应用程序的所有内容。
完整 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);
}
有效。我只需要在要冲洗的管道的字符串末尾添加换行符。例如。我用过:
printf("%s\n", str);
而不是:
printf("%s", str);
它可能看起来 'work',但那只是偶然。关闭 FILE*
的底层描述符并将其替换为另一个一定会在某些时候混淆 FILE 实现(最有可能在那个重要的演示期间)
安全的方法是使用 fdopen
从给定的套接字创建一个新的 FILE*
,然后如果您坚持使用 fscanf
/fprintf
。
fdopen
是一个 posix 函数,但 dup
也是,所以我猜你在 posix 系统上。