Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
socket与客户机服务器的读写编程_C_Sockets - Fatal编程技术网

socket与客户机服务器的读写编程

socket与客户机服务器的读写编程,c,sockets,C,Sockets,我是c程序和socket的新手,在我开始深入研究之前,我正在尝试正确理解我的概念。下面是我的代码,假设我的连接都完成了,并且进入了那些fd是clientFd的方法 服务器: writeSomething (int fd) { char str [200]; while (readLine (fd, str)) printf ("You have entered - %s\n", str); } readLine (int fd, char* str) { i

我是c程序和socket的新手,在我开始深入研究之前,我正在尝试正确理解我的概念。下面是我的代码,假设我的连接都完成了,并且进入了那些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”,MyIf else似乎不起作用


很抱歉给您添麻烦,谢谢。

您的代码非常混乱,但是,答案是

  • readLine()
    实际上是使用
    read()
    从客户端读取输入,并将其存储到
    str
    ,是的,逐字节存储。当从客户端输入读取时,您还想做什么
  • 不清楚
  • 不能使用
    ==
    比较字符串。使用
  • 注:

  • 请添加函数的返回类型。不要依赖编译器来完成你应该完成的任务
  • stdin
    读取时,
    fgets()
    读取并存储最后的
    \n
    。小心点

  • 为什么函数没有返回类型?@SouravGhosh抱歉,我也不是很确定,盲目遵循是不是不好,但不知怎么的,这段代码目前运行良好,您需要在循环中调用
    write
    ,猜猜为什么。我很困惑,您想做什么?这与套接字编程无关。如果要在进程之间进行通信,则需要IPC解决方案,例如管道。对于套接字之间的通信,您需要使用send/sendto和recv/recvfrom,具体取决于您使用的协议类型。