Java socket timeout



  • https://github.com/VyacheslavMartynenko/NetworkLab2

    In general, the reference to the project, the game of bull cows has been implemented:
    The server generates a word of 4 digits, and the client is trying to give it away. Connection and disconnected. But I can't use the time out if the user or server hasn't received messages for a long time.
    The maximum was found to be in the Client counteraller to call in the button application method after counting the function setOutTimeout, or to check the System.currentMills, pre-checked and after, everything generally works and closes, but there's a mistake in Model: Stream closed.



  • Well, I did what I could with the colts.

    class TimeoutThread extends Thread {
        private final int time;
        private boolean isStop = false;
    
    public TimeoutThread(int time) {
        super();
        this.time = time;
    }
    
    public void stopCheckTimeout() {
        this.isStop = true;
    }
    
    
    @Override
    public void run() {
        try {
            System.out.println("start");
            long endTime = System.currentTimeMillis() + time;
            count = time / 1000;
            while (!isStop) {
                count--;
                Thread.sleep(1000);
                System.out.println("ooo");
                ClientPresenter.getInstance().handleResult(String.valueOf(count));
                if (System.currentTimeMillis() > endTime) {
                    System.out.println("disc");
                    disconnect();
                    break;
                }
            }
            System.out.println("finish");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    And used:

    new Thread(() -> {
    TimeoutThread timeoutThread = new TimeoutThread(10000);
    while (status) {
    try {
    if (isReceive()) {
    timeoutThread.stopCheckTimeout(); //stop current timeout
    boolean gameFinished = check();
    if(gameFinished) {
    return;
    }

                    timeoutThread = new TimeoutThread(10000); // start new
                    timeoutThread.start();
                }
            } catch (Exception e) {
                status = false;
            }
        }
    }).start();
    


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2