我想在这个程序中设置一个计时器,以便在经过一定时间后跳出循环

I want to set a timer in this program so that it will break out of the loop if a certain period of time has passed

代码的重点是连接到客户端然后让他们猜一个按钮的游戏...然后读取输入并将其与生成的内容进行比较。我想设置一个时间限制,即在服务器关闭之前客户端必须输入多长时间。

   while(true)
        {
           try
            {

            //accept a client connection
            Socket GameServer = SSocket.accept();



            //let the server know the game is starting 
            System.out.println("Starting game...");

            //generate random number
            randnum = new Random();
            //make it be a button from 0-12
            thebutton = randnum.nextInt(11);
            //acknowledge which button was generated
            System.out.println("Button " + thebutton + " turned on");

            //writes server message to client
            BufferedReader in = new BufferedReader(new InputStreamReader(GameServer.getInputStream()));
            //make the button guessed = to whatever the client has entered
            input = in.readLine();
            //let the server know the clients response
            System.out.println("Button press acknowledged \nPlayer pressed button " + input);
            //let the client know the server acknowledged the response. 
            PrintWriter out = new PrintWriter(GameServer.getOutputStream());

            //convert user input from string to int
            buttonguess = Integer.parseInt(input);
            //compare input against number generated
            if (buttonguess == thebutton)
            {
                //if it's right print that the button is correct
                System.out.println("Player pressed the correct button");
                //add one to user score
                points += 1;
            }

            else
            {
                //if it's wrong then game over let the user know this
                System.out.println("Incorrect button pressed\nGame over!");
                //let the user know what score they have got
                System.out.println("Score = " + points);
                break;
            }

        //DataOutputStream confirmation = new DataOutputStream(SSocket.getOutputStream());

        //confirmation.writeBytes("I got your message"); //Responds to client using the DataOutputStream
        }// End try

        //if the time runs out 


        //if the number entered is incorrect format (not a number)
        catch(NumberFormatException n)
        {
            //let the user know there was a problem with their input
            System.out.println("Game over you didn't enter a proper input better luck next time \n");
            //print their score
            System.out.println("Your Score is = " + points);
            break;
        }

                catch(SocketTimeoutException a)
        {   

            System.out.println("Time up \n Game over!");
            System.out.println("Your Score is = " + points);
            //exit program
            break;
        }// End catch
        //if any kind of error occurs (usually connection error then do the following)
        catch(IOException e)
        {
            //print that error
            e.printStackTrace();

            // exit the program
            break;
        }// End catch
    }// End while()

Reader.read 方法,包括 readLine 是阻塞的,因此您不能将它们与超时结合使用。

相反,您可以使用 Reader.ready 首先测试是否可以无阻塞地读取流(即是否有任何输入要读取)。

所以你可以按照这些思路做一些事情:

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    String input = null;
    long maxWait = 5000; // 5 seconds
    long endTime = System.currentTimeMillis() + maxWait;
    boolean timeout = false;
    while (!reader.ready()) {
        synchronized(reader) {
            reader.wait(250);
        }
        if (System.currentTimeMillis() >= endTime) {
            timeout = true;
            break;
        }
    }
    if (!timeout) {
        input = reader.readLine();
    } else {
        System.out.println("timeout without input");
    }