【问题标题】:Logical problem of using fork() to handle multiple clients in socket in cc语言中使用fork()处理socket中多个客户端的逻辑问题
【发布时间】:2019-09-18 09:56:03
【问题描述】:

我目前正在使用socket编写一个骰子游戏的服务器来处理多个客户端,每次服务器开始新一轮游戏(客户端必须至少为3),应该有两个随机骰子掷出两个随机int在1-6之间,客户端需要猜解并发送给服务器。

我面临的逻辑问题是,我正在使用fork()函数来处理多个客户端,每一轮游戏都必须是一个while循环,但同时循环不断接收连接,这意味着每个game_round() 函数(掷两个骰子)运行时,程序仍然可以接收连接。

我的问题是,如何修改我的代码以使游戏仅在客户端至少为 3 个时才开始,然后为每个子进程执行后续步骤,直到只有一个客户端。

游戏逻辑是:

  1. 掷两个骰子以获得解决方案。

  2. client1 将猜测发送到服务器, 客户端 2 将猜测发送到服务器,客户端 3 发送......

  3. 服务器接收猜测并检查,如果 client1 错误,则 live-1, 如果正确,则什么也不做,将生命信息发送回客户。

  4. 返回第 1 步,直到只有一个客户获胜。

这是我的服务器代码的一部分:

    while(1){

           // Roll the dice
           game_round();

           socklen_t client_len = sizeof(client);
           client_fd = accept(server_fd, (struct sockaddr *) &client,                        &client_len);
           if(client_fd<0)
           {
                perror("connection error");
                exit(1);
           }

           printf("new client accepted.\n");

           if(childid=fork()==0)//child process
           {
                printf("child process: %d created.\n", getpid());
                printf("\n" );
                close(server_fd);// close listening

                // receive INIT and send information back
                init(client_fd, info);

                sleep(2);

                // send game begun message
                begun(client_fd);

                sleep(2);

                //send guess information
                guess(client_fd);

                sleep(2);

                //receive client's moves and process
                recv_proce_move(client_fd, move);

                check(info, round, move);

                sleep(2);

                // send lives back to clients, if lives is 0, close 
                   the child process
                // if the client's live is 0, close the connection
                send_lives(client_fd, move, info);
          }
          if(childid == 0){
               printf("game over");
               break;
          }
     }

【问题讨论】:

  • 发送答案的代码在哪里?你如何连接到服务器?
  • 我把send函数放在了init()、guess()等新定义的函数里面,只是简单的把一些信息发回给客户端

标签: c sockets client fork


【解决方案1】:

您需要将您的套接字放入 select() 函数之类的东西中。选择函数允许您同时阻塞和等待多个套接字和文件描述符上的事件。

这是一个很好的例子: https://www.gnu.org/software/libc/manual/html_node/Server-Example.html

【讨论】:

  • 先谢谢了,在使用 select() 函数后,我还需要使用 fork() 函数来执行发送和检查步骤吗?因为我意识到 select() 使用 for 循环来循环该数组中的每个客户端,所以我不太确定消息是否或者我可以说每个游戏回合的信息会同时到达每个客户端。
猜你喜欢
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2014-10-06
  • 2014-05-23
  • 1970-01-01
相关资源
最近更新 更多