服务器:
package net;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Exercise31_02Server extends Application {
private ExecutorService executor = Executors.newFixedThreadPool(1); //线程池(管理线程数量)
private TextArea textArea = new TextArea(); //文本区域(显示信息)
private static final int SERVER_PORT = 8000; //端口号
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
//文本区域设置属性
textArea.setPrefColumnCount(40);
textArea.setPrefRowCount(10);
textArea.setEditable(false);
Scene scene = new Scene(new ScrollPane(textArea));
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise31_02Server");
primaryStage.show();
//启动线程
new Thread(this::startServer).start();
}
/** 启动服务器 */
private void startServer() {
try {
//创建服务器套接字
ServerSocket server = new ServerSocket(SERVER_PORT);
Platform.runLater(() -> textArea.appendText(this.getClass().getSimpleName() + " started at " + new Date() + "\n"));
while (true) {
//创建套接字(连接客户端)
Socket socket = server.accept();
Platform.runLater(() -> textArea.appendText("Connected to a client at " + new Date() + "\n"));
//为连接的客户端分配一个线程
executor.execute(new HandleClient(socket));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
executor.shutdown();
}
}
/** 内部类-处理一个客户端 */
private class HandleClient implements Runnable {
private Socket socket; //连接客户端的套接字
public HandleClient(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
final double POUND = 0.45359237, INCH = 0.0254;
DataInputStream inputFromClient = null; //输入、输出流
DataOutputStream outputToClient = null;
try {
inputFromClient = new DataInputStream(socket.getInputStream());
outputToClient = new DataOutputStream(socket.getOutputStream());
while (true) {
//获取客户端数据
double weightInPounds = inputFromClient.readDouble();
double heightInInches = inputFromClient.readDouble();
double bmi = (weightInPounds * POUND) / Math.pow(heightInInches * INCH, 2);
String status;
//判断字符串状态
if (bmi < 20) status = "Underweight";
else if (20 <= bmi && bmi <= 25) status = "Normal weight";
else status = "Overweight";
//写数据到客户端
outputToClient.writeDouble(bmi);
outputToClient.writeUTF(status);
Platform.runLater(() ->
textArea.appendText("Weight: " + weightInPounds + "\n" +
"Height: " + heightInInches + "\n" +
"BMI is " + bmi + " " + status + "\n\n"));
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try { //关闭流
if (inputFromClient != null) inputFromClient.close();
if (outputToClient != null) outputToClient.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
}
客户端:
package net;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Exercise31_02Client extends Application {
private TextField weightInPounds = new TextField(); //体重
private TextField heightInInches = new TextField(); //身高
private Button submit = new Button("Submit"); //提交
private TextArea message = new TextArea(); //文本区域(显示信息)
private static final String HOST = "localhost"; //主机/IP地址
private static final int SERVER_PORT = 8000; //端口号
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
//总面板
BorderPane pane = new BorderPane(new ScrollPane(message));
pane.setTop(getTopPane());
//文本区域设置属性
message.setPrefRowCount(6);
message.setPrefColumnCount(30);
message.setEditable(false);
//按钮设置动作事件
submit.setOnAction(event -> handleSubmit());
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise31_02Client");
primaryStage.show();
}
/** 返回顶部面板 */
private GridPane getTopPane() {
//网格面板(放置文本域)
GridPane pane = new GridPane();
pane.setStyle("-fx-hgap: 10px; -fx-vgap: 5px;");
pane.addRow(0, new Label("Weight in pounds:"), weightInPounds);
pane.addRow(1, new Label("Height in inches:"), heightInInches);
pane.add(submit, 2, 1);
//文本域设置属性
weightInPounds.setAlignment(Pos.BOTTOM_RIGHT);
heightInInches.setAlignment(Pos.BOTTOM_RIGHT);
weightInPounds.setPrefColumnCount(13);
heightInInches.setPrefColumnCount(13);
return pane;
}
/** 提交信息给服务器 */
private void handleSubmit() {
Socket socket = null; //客户端套接字
DataInputStream inputFromServer = null; //输入流
DataOutputStream outputToServer = null; //输出流
try {
socket = new Socket(HOST, SERVER_PORT);
inputFromServer = new DataInputStream(socket.getInputStream());
outputToServer = new DataOutputStream(socket.getOutputStream());
double weight = Double.parseDouble(this.weightInPounds.getText().trim());
double height = Double.parseDouble(this.heightInInches.getText().trim());
//发送数据到服务器
outputToServer.writeDouble(weight);
outputToServer.writeDouble(height);
//接受服务器数据
double bmi = inputFromServer.readDouble();
String status = inputFromServer.readUTF();
Platform.runLater(() ->
message.appendText("Weight: " + weight + "\n" +
"Height: " + height + "\n" +
"BMI is " + bmi + " " + status + "\n\n"));
this.weightInPounds.setText("");
this.heightInInches.setText("");
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try { //关闭与服务器的连接
if (socket != null) socket.close();
if (inputFromServer != null) inputFromServer.close();
if (outputToServer != null) outputToServer.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}