Javafx,确定从套接字读取的特定超时



在下面的代码中,在一个线程(而不是UI线程(中,我试图从套接字读取数据。但在每种状态下,如果时间超过3秒,我都想打破while循环。我该怎么做?

您可以在代码中找到一些注释

System.out.println(loginMsg);//send login message to server
while ((fromServer = sInput.readLine()) != null) {
    switch (state) {
        case 0:
            if (fromServer.equals("*2*1#")) //Login was successful
            {
                sOutput.println(msg); // send another message to server to enter some data into database
                state = 1;
            } else if (fromServer.equals("*2*0#")) //Login was not successful
            {
                motor1CommandString = "access denied";
                state = 3;
            }
            break;
        case 1:
            if (fromServer.equals("*6*1#"))
            {
                motor1CommandString = "message sent";
                state = 2;
            } else if ((fromServer.equals("*6*2#")) /*device is not online */ ||     (fromServer.equals("*6*0#")))  /*for some reason device is not reachable */{
                motor1CommandString = "No Connection to device";
                state = 3;
            }
           break;
        case 2:
            if (fromServer.equals(ACK)) //device has received the message and replied back
                state = 3;
        break;
    }
    if (state == 3) {
        break;
}

}

在套接字上调用setSoTimeout(在尝试读取之前(。如果在超时到期之前没有读取任何数据,则readLine将抛出SocketTimeoutException。您可以在循环之外捕获该异常。

相关内容

  • 没有找到相关文章

最新更新