【发布时间】:2019-09-18 09:56:03
【问题描述】:
我目前正在使用socket编写一个骰子游戏的服务器来处理多个客户端,每次服务器开始新一轮游戏(客户端必须至少为3),应该有两个随机骰子掷出两个随机int在1-6之间,客户端需要猜解并发送给服务器。
我面临的逻辑问题是,我正在使用fork()函数来处理多个客户端,每一轮游戏都必须是一个while循环,但同时循环不断接收连接,这意味着每个game_round() 函数(掷两个骰子)运行时,程序仍然可以接收连接。
我的问题是,如何修改我的代码以使游戏仅在客户端至少为 3 个时才开始,然后为每个子进程执行后续步骤,直到只有一个客户端。
游戏逻辑是:
掷两个骰子以获得解决方案。
client1 将猜测发送到服务器, 客户端 2 将猜测发送到服务器,客户端 3 发送......
服务器接收猜测并检查,如果 client1 错误,则 live-1, 如果正确,则什么也不做,将生命信息发送回客户。
返回第 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()等新定义的函数里面,只是简单的把一些信息发回给客户端