gpt4 book ai didi

c - 套接字编程读写与客户端服务器

转载 作者:行者123 更新时间:2023-11-30 17:21:47 24 4
gpt4 key购买 nike

我是 C 程序和套接字的新手,在开始深入研究之前,我试图弄清楚我的概念。下面是我的代码,假设我的连接已全部完成,并进入其中 fd 是 clientFd 的那些方法。

服务器:

writeSomething (int fd)
{
char str [200];

while (readLine (fd, str))
printf ("You have entered - %s\n", str);
}

readLine (int fd, char* str)
{
int n;
do /* Read characters until NULL or end-of-input */
{
n = read (fd, str, 1); /* Read one character */
}
while (n > 0 && *str++ != 0);
return (n > 0); /* Return false if end-of-input */
}

客户:

readSomething (int fd)
{
print_intro();
char input[200];
do {
printf ("Please enter something > ");
fgets(input, 200, stdin);
if (input == "end")
{
printf ("*** Thank you for using, have a nice day! ***");
close (fd);
} else {
write (fd, input, strlen (input) + 1);
}

} while ( input == "")
}

我的问题:1)readLine()方法真的有必要吗?或者我可以从客户端输入中读取并存储到变量“str”中吗?2)如果是,我如何将输入存储到“str”中?3)如何制作无限循环来提示输入,直到用户输入“end”,我的 if else 似乎不起作用?

抱歉给您带来麻烦,谢谢。

最佳答案

您的代码非常困惑,但是答案是。

  1. readLine()实际上使用read()从客户端读取输入并将其存储到str,是的,一个字节一个字节。 从客户端输入读取时,您还想做什么?
  2. 不清楚。
  3. 您无法使用 == 比较字符串。使用strcmp()/ strncmp() .

注意:

  1. 请添加函数的返回类型。不要依赖编译器来完成您应该执行的任务。
  2. stdin 读取时,fgets() 读取并存储最后的 \n。照顾好这一点。

关于c - 套接字编程读写与客户端服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28187414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com