我正在用C语言中的select()制作一个客户机服务器,它模拟了一个快餐店或其他东西。
我有客户在1到5点之间随意点“菜”。服务器每30秒决定一次。所有客户最喜欢的食物是什么。他为这些客户服务,他们建立了紧密的联系,而对于其他客户,他会给他们发送一个等待的信息。没有服务的客户再试两次,否则就离开。
我的问题是,如何让服务器每30秒检查一次。他们的命令是什么?
我试着做了一个数组,但我不知道如何让服务器每30秒“检查”一次。然后将数组设置为0。
这是伪代码:

**client**

patience=0;served=0;
do
{send random 1-5
receieve message. if 1->served=1; if 0, patience++;
}while patience !=3 and served!=1;

if served==1 send -1
else send -2
close connection

**Server**
while(1)
{
serves clients in a concurent manner
select
adds client in socket list
serves client


waits message
if 1-5 adds in vector
//here I don't know how to make it wait for 30 sec.
//If I put sleep(30), it's going to sleep for each client every time. I want it to permanently check every 30 sec and send messages to clients.
send respones(0 or 1, depending on if the max order is the same as the client's)

if -1, thanks for the food
if -2, going somewhere else

close client connection
}

最佳答案

您可能想在循环中尝试sleep()函数,它所做的是暂停程序这么长时间,然后执行下面的语句。

sleep(30);

我想是你想要的。查看here了解更多有关睡眠的信息。
你的代码应该是:
for(i=0; i<=100; i++)//Checks 100 times
{
    sleep(30);
    checkserverforupdate();

}

更新
代码:
while(1){//runs infinite times
    sleep(30);//pauses here for 30 seconds everytime before/after running the following code

    *client**

    patience=0;served=0;
    do
    {send random 1-5
    receieve message. if 1->served=1; if 0, patience++;
    }while patience !=3 and served!=1;

    if served==1 send -1
    else send -2
    close connection

    **Server**
    while(1)
    {
    serves clients in a concurent manner
    select
    adds client in socket list
    serves client


    waits message
    if 1-5 adds in vector
    //here I don't know how to make it wait for 30 sec.
    //If I put sleep(30), it's going to sleep for each client every time. I want it to permanently check every 30 sec and send messages to clients.
    send respones(0 or 1, depending on if the max order is the same as the client's)

    if -1, thanks for the food
    if -2, going somewhere else

    close client connection
    }
}

看看sleep(30)会发生什么,程序暂停30秒,然后执行在它之后编写的代码,如果将它放入while循环,它每次都会等待。
更新2:
如何在C中获取当前时间的代码:
here
/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );

  return 0;
}

更新3:
所以你的代码应该是这样的:
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );


  All of your code here

  and then get the time again,
  time_t rawtime1;
  .....

  and then you may calculate the difference between them and put a sleep statement as you wish. If the time you want it to pause is in x then,

  sleep(x);

  return 0;

关于c - 客户-服务器餐厅模拟,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21202564/

10-11 15:15
查看更多