需求
- 利用TCP协议实现一个可以从服务器读取时间的网络程序。
- 将该程序的客户端改为一个可以显示服务器时间的图形时钟界面,它每隔一秒从服务器读取服务器当前时间。
界面
客户端代码
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class DaytimeClient extends Application {
public static void main(String[] args){
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Pane flowPane = new Pane();
flowPane.getChildren().addAll(paintTime(250));
Pane childPane = new Pane();
flowPane.getChildren().add(childPane);
Socket socket = new Socket("localhost",2007);
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
new Timer().schedule(new TimerTask() {
@Override
public void run() {
Platform.runLater(new Runnable() {
@Override
public void run() {
try {
childPane.getChildren().clear();
paint(inputStream,childPane);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
},500,1000);
Scene scene = new Scene(flowPane,500,500);
primaryStage.setScene(scene);
primaryStage.show();
}
private List<Node> paintTime(double r){
List<Node> lines = new ArrayList<>();
Circle circle = new Circle(250,250,240);
circle.setFill(Color.rgb(255,255,255));
circle.setStroke(Color.rgb(139,242,241));
circle.setStrokeWidth(20);
Circle inCircle = new Circle(