从NTPUDPClient获取日期和时间有时会失败

时间:2016-08-24 12:05:08

标签: date time timeout udpclient

我使用NetBeans工作了6个月,并且我从未遇到过这样的问题。它开始于我添加了org.apache.commons库(我需要它来从在线服务器获取时间),当我运行程序时,有时一切都很顺利,有时它会挂起运行状态在后台创建一个进程。这是使用主要方法的类。

package samplefx.ctrl;

import java.io.IOException;
import java.net.InetAddress;
import java.sql.Date;
import java.text.ParseException;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;

public class Optilight extends Application {

    public static EntityManagerFactory emf;
    EntityManager em;

    @Override
    public void start(Stage primaryStage) throws IOException, ParseException {

        emf = Persistence.createEntityManagerFactory("SampleFXPU");

        String TIME_SERVER = "time-a.nist.gov";
        NTPUDPClient timeClient = new NTPUDPClient();
        InetAddress inetAddress = InetAddress.getByName(TIME_SERVER);
        TimeInfo timeInfo = timeClient.getTime(inetAddress);
        long returnTime = timeInfo.getMessage().getTransmitTimeStamp().getTime();
        Date time = new Date(returnTime);

        Access access = new Access();
        String fix = "XC193283R";
        String var = access.Y();

        Date start = Date.valueOf("2016-08-23");
        Date end = Date.valueOf("2016-08-31");

        Boolean j = false;
        if (start.before(time) && time.before(end)) {
            j = true;
        }
        boolean i = false;
        if (fix.equals(var)) {
            i = true;
        }

        if (!j || !i) {

            System.exit(0);

        }

        // load main form in to VBox (Root)
        BorderPane mainPane = (BorderPane) FXMLLoader.load(getClass().getResource("/samplefx/view/Login.fxml"));
        // add main form into the scene
        Scene scene = new Scene(mainPane);

        //primaryStage.setTitle("Optilight 2.2.1");
        primaryStage.setScene(scene);
        primaryStage.initStyle(StageStyle.UNDECORATED);

        //primaryStage.setMaximized(true);    // make the main form fit to the screen
        primaryStage.show();

        primaryStage.setOnCloseRequest(e -> {
            emf.close();
            Platform.exit();
            System.exit(0);

        });

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        launch(args);

    }
}

1 个答案:

答案 0 :(得分:1)

我终于找到了答案,这是一个服务器超时问题。我添加了这两行: 此行后timeClient.open(); timeClient.setSoTimeout(5000); NTPUDPClient timeClient = new NTPUDPClient();