简体   繁体   中英

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

The point of the code is a game to connect to client and then make them guess a button... the input is then read and compared to to what was generated. I wish to set a time limit to how long the client has to enter this before the server shuts down.

   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 methods, including readLine are blocking, so you can't combine them with a timeout.

Instead you can use Reader.ready to first test if the stream can be read without blocking (ie whether there is any input to read).

So you could do something along these lines:

    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");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM